Java8计算两个日期相差的天数
1 获取总的相差间隔
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate now = LocalDate.now();
System.out.println("now:"+now);
LocalDate startDate = LocalDate.parse("2021-05-26",formatter);
System.out.println("相差天数:" + startDate.until(now, ChronoUnit.DAYS));
System.out.println("相差月数:" + startDate.until(now, ChronoUnit.MONTHS));
System.out.println("相差年数:" + startDate.until(now, ChronoUnit.YEARS));

2 获取单独日期间隔
LocalDate start = LocalDate.of(2021,5,1);
LocalDate end = LocalDate.now();
System.out.println("end:"+end);
Period next = Period.between(start,end);
System.out.println("相差天数:"+next.getDays());//相差天数
System.out.println("相差月数:"+next.getMonths());//相差月份
System.out.println("相差年"+next.getYears());//相差年份

如果想要获取更加精确的时间差值可以用Duration 类
Duration类表示秒或纳秒时间间隔,适合处理较短的时间,需要更高的精确性。我们能使用between()方法比较两个瞬间的差 。
想要快速入手java开发小知识,快来关注公众号:爪哇开发吧!每天会不定时的进行更新。


浙公网安备 33010602011771号