记录日常开发中Java 8时间API的常用的日期转换代码。
注意:下文中,都以LocalDateTime为例,在不声明的情况下如下方法一般都适用于Java8中LocalDate、LocalDateTime、OffsetDateTime、ZonedDateTime等时间类,不适用某些类时会在文中有提醒。
年初年末
- 使用TemporalAdjusters工具类。
LocalDateTime.now().with(TemporalAdjusters.firstDayOfYear()); // 2023-01-01T14:11:27.062
- 使用
with
、adjustInto
方法,通过TemporalAdjuster
实现类(如MonthDay
)来调整时间。后面的调整日期、时分秒都可以借鉴下面的方法来实现。
MonthDay lastDayOfMonth = MonthDay.of(12, 31);
LocalDateTime with = LocalDateTime.now().with(lastDayOfMonth);
// 等价于
LocalDateTime adjustInto = (LocalDateTime) lastDayOfMonth.adjustInto(LocalDateTime.now());
TemporalAdjusters的方法:
TemporalAdjusters.firstDayOfYear()
:将月份和日期调整至1月1日Tem