Duration与Period区别
| 类 | 用途 | 基于 |
| Duration | 时间间隔 | 秒/纳秒 |
| Period | 日期间隔 | 年/月/日 |
Duration使用
Duration duration = Duration.ofHours(2);
Duration between = Duration.between(start, end);
duration.toMinutes();
duration.toMillis();
Period使用
Period period = Period.ofDays(7);
Period between = Period.between(date1, date2);
period.getYears();
period.getMonths();
period.getDays();
ChronoUnit
long days = ChronoUnit.DAYS.between(date1, date2);
long hours = ChronoUnit.HOURS.between(time1, time2);
小结
- Duration用于时间间隔(秒为单位)
- Period用于日期间隔(年月日)
- ChronoUnit提供通用时间单位计算
- 选择合适类型取决于具体场景