在 Java中,我们要获取一个时间段的天数,我们可以使用下面几种方式:
LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.of(2020, 5, 1);主要通过Period类方法getYears(),getMonths() 和 getDays()来计算.
示例:
/**
* @Author liuwenxu.com (2020-04-26)
*
* @param start
* @param end
* @return void
**/
private static void testPeriod(LocalDate start, LocalDate end) {
log.info("startPeriod : {}", start);
log.info("endPeriod : {}", end);
Period period = Period.between(start, end);
log.info("[{}~{})之间共有:{}年,{}月,{}日", start, end, period.getYears(), +period.getMonths(), +period.getDays());
}结果:
- startPeriod : 2020-01-01
- endPeriod : 2020-05-01
- [2020-01-01~2020-05-01)之间共有:0年,4月,0日提供了使用基于时间的值测量时间量的方法:
天数:toDays();
小时:toHours();
分钟:toMinutes();
秒数:toMillis();
纳秒:toNanos();
示例: 转换日期时提前一天
/**
* @Author liuwenxu.com (2020-04-26)
*
* @param start
* @param end
* @return void
**/
private static void testDuration(LocalDate start, LocalDate end) {
Instant startInstant = start.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant endInstant = end.atStartOfDay(ZoneId.systemDefault()).toInstant();
log.info("startInstant : {}", startInstant);
log.info("endInstant : {}", endInstant);
Duration between = Duration.between(startInstant, endInstant);
log.info("[{}~{})之间共有:{}天", start, end, between.toDays());
}结果:
- startInstant : 2019-12-31T16:00:00Z
- endInstant : 2020-04-30T16:00:00Z
- [2020-01-01~2020-05-01)之间共有:121天ChronoUnit类使用between()方法求在单个时间单位内测量一段时间,例如天数、小时、周或秒等。
示例:
/**
* @Author liuwenxu.com (2020-04-26)
*
* @param start
* @param end
* @return void
**/
private static void testChronoUnit(LocalDate start, LocalDate end) {
log.info("startChronoUnit : {}", start);
log.info("endChronoUnit : {}", end);
long daysDiff = ChronoUnit.DAYS.between(start, end);
log.info("[{}~{})之间共有:{}天", start, end, daysDiff);
}结果:
- startInstant : 2020-01-01
- endInstant : 2020-05-01
- [2020-01-01~2020-05-01)之间共有:121天Q.E.D.