【LocalDate】获取两个日期间相差的年数、月数、天数

常见的错误做法!!!

比如获取相差月:使用Period.between(date1,date2).getMonth()

LocalDate date1 = LocalDate.of(2022,2,10);
LocalDate date2 = LocalDate.of(2022,3,8);
LocalDate date3 = LocalDate.of(2022,1,20);
LocalDate date4 = LocalDate.of(2020,1,20);
System.out.println(Period.between(date1, date2).getMonths());
System.out.println(Period.between(date3, date1).getMonths());
System.out.println(Period.between(date4, date1).getMonths());

输出值:0 0 0 ,显然不是我们想要的。

正确做法

LocalDate date1 = LocalDate.of(2022, 2, 10);
LocalDate date2 = LocalDate.of(2020, 1, 20);
//年差
int years = date1.getYear() - date2.getYear();
//月差
int months = years * 12 + (date1.getMonthValue() - date2.getMonthValue());
//天差
long days = date1.toEpochDay() - date2.toEpochDay();
System.out.println(years);
System.out.println(months);
System.out.println(days);

你可能感兴趣的:(java,开发语言)