例如24.05.2017
和31.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);
}
看起来不错 - 但是由于您使用的是系统时区,因此您可以跳过它。直接使用即时也很好 - 无需先转换为 LocalDate。您还可以跳过局部变量并立即执行日期到即时转换:
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);
}
是的,你走对了!
由于您要求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);