17.时间矫正器

49 阅读1分钟

17.时间矫正器

有时候我们需要如下调整:

将日期调整到下个月的第一天等操作。

虽然我们可以通过withXxx操作时间,这时我们通过时间矫正器效果可能更好。

@Test
@DisplayName("时间矫正器")
public void test9()  {
    LocalDateTime now = LocalDateTime.now();

    TemporalAdjuster adjuster = (temporal -> {
        LocalDateTime dateTime = (LocalDateTime) temporal;
        LocalDateTime nextMonth = dateTime.plusMonths(1).withDayOfMonth(1);
        System.out.println("nextMonth = " + nextMonth);
        return nextMonth;
    });

    LocalDateTime nextMonth = now.with(adjuster);
    System.out.println("nextMonth = " + nextMonth);
}
nextMonth = 2023-05-01T22:16:24.193
nextMonth = 2023-05-01T22:16:24.193

直接plusXxx就可以了,为神马要用时间矫正器呢 ?

@Test
@DisplayName("时间矫正器2")
public void test10()  {
    LocalDateTime now = LocalDateTime.now();
    // 这个月的第一天
    LocalDateTime thistMonth = now.with(TemporalAdjusters.firstDayOfMonth());
    System.out.println("thistMonth = " + thistMonth);

    //下个月的第一天
    LocalDateTime nextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
    System.out.println("nextMonth = " + nextMonth);
    
    // 等等很多内置方法
}
thistMonth = 2023-04-01T22:20:13.288
nextMonth = 2023-05-01T22:20:13.288