LocalDate获取间隔天数
如果使用Period
获取时间间隔,如果两个时间跨月了,那获取的数据是不准确的。
public static void main(String[] args) {
LocalDate realStartDate = LocalDate.of(2021, 8, 26);
LocalDate realEndDate = LocalDate.of(2021, 9, 27);
Period duration = Period.between(realStartDate, realEndDate);
int days = duration.getDays()+1;
System.out.println(days);
}
输出: 2
如果想要得到我们的结果,那就需要使用LocalDate
的toEpochDay()
方法,然后计算差值。
public static void main(String[] args) {
LocalDate realStartDate = LocalDate.of(2021, 8, 26);
LocalDate realEndDate = LocalDate.of(2021, 9, 27);
Period duration = Period.between(realStartDate, realEndDate);
int days = duration.getDays()+1;
System.out.println(days);
int days2 = Math.toIntExact(realEndDate.toEpochDay() - realStartDate.toEpochDay());
System.out.println(days2);
}
输出: 2
32
ok。
网友评论