本文目录#

TemporalAdjuster 概述#

TemporalAdjuster 定义了时间调整策略,适用于 LocalDate, LocalDateTime 等类型。通过调整器可以自定义业务日历,如下个工作日、月末、财务周期。

内置调整器#

  • next(DayOfWeek)previousOrSame(DayOfWeek)
  • firstDayOfMonth()lastDayOfQuarter()
  • lastInMonth(DayOfWeek) 等。

自定义调整器#

1
2
3
4
5
6
7
8
9
TemporalAdjuster nextWorkday = temporal -> {
LocalDate date = LocalDate.from(temporal);
do {
date = date.plusDays(1);
} while (EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).contains(date.getDayOfWeek()));
return temporal.with(date);
};

LocalDate nextBizDay = LocalDate.now().with(nextWorkday);

业务建模#

  • 财务周期:结合 YearMonth, TemporalAdjuster 计算账单周期;
  • SLAs:使用 Duration, PeriodChronoUnit 计算时限;
  • 时区转换:ZonedDateTime.withZoneSameInstant() 与调整器组合。

日期与时间线库#

  • java.time + ZoneId
  • ThreeTen-Extra 提供额外调整器(如营业日历);
  • JSR-310 兼容 libs(Joda-Time 迁移)。

自检清单#

  • 是否在业务逻辑中替换繁琐的手写日期运算?
  • 是否考虑节假日自定义调整器与外部配置?
  • 是否保证时间转换使用 ZoneId 而非系统默认?

参考资料#


本作品系原创,采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,转载请注明出处。