在 Java中,我们要获取一个时间段的天数,我们可以使用下面几种方式:
- Period @since 1.8
- Duration @since 1.8
- ChronoUnit @since 1.8
一. 参数声明
|
|
二.Period类
主要通过Period
类方法getYears()
,getMonths()
和 getDays()
来计算.
示例:
|
|
结果:
|
|
三.Duration类
提供了使用基于时间的值测量时间量的方法:
天数: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());
}
结果:
|
|
四.ChronoUnit类
ChronoUnit类使用between()
方法求在单个时间单位内测量一段时间,例如天数、小时、周或秒等。
示例:
|
|
结果:
|
|