计算两个时间之间的时间差:
分别使用Period.between和ChronoUnit方法测试
测试结果如下:
结果发现Period.between的方法是使用年月日分别进行比对,得出的结果不是我们想要的。
解决方案:采用ChronoUnit的比较方法
完整代码如下:
1 public static void main(String[] args) { 2 3 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 4 5 LocalDate time = LocalDate.now(); 6 LocalDate date = LocalDate.parse("2020-03-01 12:00:00", dateTimeFormatter); 7 8 Period period = Period.between(date,time); 9 System.out.println("period.getDays()计算出的天数时间差:"+period.getDays()); 10 System.out.println("period.getDays()计算出的月数时间差:"+period.getMonths()); 11 System.out.println("period.getDays()计算出的年数时间差:"+period.getYears()); 12 System.out.println("ChronoUnit.DAYS.between计算出的天数时间差:"+ChronoUnit.DAYS.between(date,time)); 13 System.out.println("ChronoUnit.DAYS.between计算出的月数时间差:"+ChronoUnit.MONTHS.between(date,time)); 14 System.out.println("ChronoUnit.DAYS.between计算出的年数时间差:"+ChronoUnit.YEARS.between(date,time)); 15 }