获取Java8中两个日期的差值(天数)的最简单方法是将其作为短基元类型
例如获取Java8中两个日期的差值(天数)的最简单方法是将其作为短基元类型,java,long-integer,short,date-difference,Java,Long Integer,Short,Date Difference,例如2017年5月24日和2017年5月31日 将是7 我走的路对吗 private short differenceOfBillingDateAndDueDate(Date billingDate, Date dueDate) { LocalDate billingLocalDate = billingDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate dueLocalDate =
2017年5月24日
和2017年5月31日
将是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和ChronUnit
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。您还可以跳过局部变量并立即执行日期到即时的转换:
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);
}