定义具有整数的日期差的最大时间单位

Tom*_*rmi 3 java duration date java-time localdate

我有 2 个日期:

LocalDate date1 = LocalDate.now().minusDays(40);
LocalDate date2 = LocalDate.now();
Run Code Online (Sandbox Code Playgroud)

我想弄清楚我可以选择的最大时间单位是什么来定义两者之间的差异(天、月、年),并获取它的数字。我认为,对我来说完美的解决方案是 if Durationapi java.timehad alsotoMonthsParttoYearsPartas it has toDaysPart. 这样我就可以这样做:

Duration dif = Duration.between(date1, date2);

long daysPart = dif.toDaysPart();
if (daysPart > 0) {
    return ChronoUnit.DAYS.between(date1, date2);
}

long monthPart = dif.getMonthsPart();
if (monthPart > 0) {
    return ChronoUnit.MONTHS.between(date1, date2);
}

long yearPart = dif.getYearsPart();
if (yearPart > 0) {
    return ChronoUnit.YEARS.between(date1, date2);
}

throw new Exception("no difference");
Run Code Online (Sandbox Code Playgroud)

但API中并没有这样的方法。是否有另一个包可以提供此功能,或者您知道实现我的目标的不同方法吗?

Arv*_*ash 5

长话短说

使用Period而不是Duration.

演示

import java.time.LocalDate;
import java.time.Period;

class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate fortyDaysAgo = today.minusDays(40);
        Period period = Period.between(fortyDaysAgo, today);
        System.out.println(period);
        System.out.printf("%d year(s) %d month(s) %d day(s)%n", period.getYears(), period.getMonths(),
                period.getDays());
    }
}
Run Code Online (Sandbox Code Playgroud)

示例运行的输出:

P1M9D
0 year(s) 1 month(s) 9 day(s)
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。