2 个回答

可以利用joda-time对时间进行方便的操作。

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.9</version>
</dependency>

利用其中的IntervalPeriod类即可完成你的需求。

Interval interval = new Interval(d1.getTime(), d2.getTime()); //d1,d2为Date类型
Period p = interval.toPeriod(); //得到相差的时间段
p.getDays()    //相差天数
p.getHours()   //相差小时
p.getMinutes() //相差分钟
p.getSeconds() //相差秒

按照我的理解,2018-04-012018-08-02 应该是相差 4 个月零 1 天。
然后这是按照我的理解写出来的代码(基于 Java8):

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateDiff {

    static int[] getDiff(LocalDate start, LocalDate end) {

        if (!start.isBefore(end)) {
            throw new IllegalArgumentException("Start must not be before end.");
        }

        int year1 = start.getYear();
        int month1 = start.getMonthValue();
        int day1 = start.getDayOfMonth();

        int year2 = end.getYear();
        int month2 = end.getMonthValue();
        int day2 = end.getDayOfMonth();

        int yearDiff = year2 - year1;     // yearDiff >= 0
        int monthDiff = month2 - month1;

        int dayDiff = day2 - day1;

        if (dayDiff < 0) {
            LocalDate endMinusOneMonth = end.minusMonths(1);   // end 的上一个月
            int monthDays = endMinusOneMonth.lengthOfMonth();  // 该月的天数

            dayDiff += monthDays;  // 用上一个月的天数补上这个月差掉的日子

            if (monthDiff > 0) {   // eg. start is 2018-04-03, end is 2018-08-01
                monthDiff--;

            } else {  // eg. start is 2018-04-03, end is 2019-02-01
                monthDiff += 11;
                yearDiff--;

            }
        }

        int[] diff = new int[2];

        diff[0] = yearDiff * 12 + monthDiff;
        diff[1] = dayDiff;

        return diff;
    }

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2018, 4, 3);

        LocalDate[] endDates = {
                LocalDate.of(2018, 4, 5),
                LocalDate.of(2018, 10, 6),
                LocalDate.of(2019, 4, 5),
                LocalDate.of(2019, 10, 6),
                LocalDate.of(2019, 3, 3),
                LocalDate.of(2019, 3, 1),
                LocalDate.of(2019, 2, 1),
                LocalDate.of(2019, 2, 2),
        };

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (LocalDate end : endDates) {
            int[] diff = getDiff(startDate, end);
            System.out.printf("%s - %s = %2d 个月零 %-2d 天\n",
                    formatter.format(end), formatter.format(startDate), diff[0], diff[1]);
        }
    }
}

运行结果:
运行结果

刚发现原来 Java8 已经提供了解决这个问题 API,所以 getDiff 方法可以简化为:

static int[] getDiff(LocalDate start, LocalDate end) {
    if (!start.isBefore(end)) {
        throw new IllegalArgumentException("Start must not be before end.");
    }

    Period period = Period.between(start, end);

    int years = period.getYears();
    int months = period.getMonths();
    int days = period.getDays();

    return new int[] {years * 12 + months, days};
}
推荐问题
宣传栏