Period
String date1 = "2019-01-03";
String date2 = "2021-12-31";
LocalDate localDate1 = LocalDate.parse(date1, dateTimeFormatter);
LocalDate localDate2 = LocalDate.parse(date2, dateTimeFormatter);
Period period = Period.between(localDate1, localDate2.plusDays(1));
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
结果:
如果要计算两个日期间隔多少天需使用
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date1 = "2019-01-03";
String date2 = "2021-12-31";
LocalDate localDate1 = LocalDate.parse(date1, dateTimeFormatter);
LocalDate localDate2 = LocalDate.parse(date2, dateTimeFormatter);
Long days = localDate2.toEpochDay()-localDate1.toEpochDay();
System.out.println(days);
结果:
注意:计算区间是 [2019-01-03,2021-12-31),注意边界值