获取 Java 8 中两个日期的差异(天数)的最简单方法作为 Short 原始类型

Simplest way to get the difference (amount of days) of two dates in Java 8 as a Short primitive type

例如24.05.201731.05.2017的区别 将是 7

我走的路对吗?

private short differenceOfBillingDateAndDueDate(Date billingDate, Date dueDate) {

    LocalDate billingLocalDate = billingDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

    LocalDate dueLocalDate = dueDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

    return (short) ChronoUnit.DAYS.between(billingLocalDate,dueLocalDate);
}

是的,你走对了!

既然你要求 java8 你可以使用 LocalDate 和 ChronoUnit

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2000, Month.JANUARY, 1);
long period = ChronoUnit.DAYS.between(today, birthday);

System.out.println(period);

看起来不错 - 但无论如何您都在使用系统时区,您可以跳过它。直接使用 Instant 也很好 - 无需先转换为 LocalDate。您也可以跳过局部变量并立即执行 Date 到 Instant 转换:

public static short differenceOfBillingDateAndDueDate(Date billingDate, Date dueDate) {
    return (short)ChronoUnit.DAYS.between(
              billingDate.toInstant()
             ,dueDate.toInstant());
}

或更短:

public static short differenceOfBillingDateAndDueDate(Date billingDate, Date dueDate) {
    return (short)billingDate.toInstant().until(dueDate.toInstant(), ChronoUnit.DAYS);
}