2

在 Java 8 中,我发现的是

TemporalAdjuster temporal = dayOfWeekInMonth(1,DayOfWeek.MONDAY) 

给出一个月的第一个星期一的时间,并且

next(DayOfWeek.MONDAY)

给出特定日期之后的下周一。

但我想在特定日期之后找到第 n 个星期一。

例如,我想要 2017-06-06 之后的第 2 个星期一,它应该是 2017-06-19

dayOfWeekInMonth(2,DayOfWeek.MONDAY)

会给我 2017-06-12 和

next(DayOfWeek.MONDAY) 

对于第 n 个 DayOfWeek 的指标,当然没有参数。它将给出下一个第一个星期一,即 2017-06-12。

我如何在不循环的情况下计算它?

4

1 回答 1

5

Write an implementation of the TemporalAdjuster interface.

Find the next monday, then add (N - 1) weeks:

public static TemporalAdjuster nextNthDayOfWeek(int n, DayOfWeek dayOfWeek) {
    return temporal -> {
        Temporal next = temporal.with(TemporalAdjusters.next(dayOfWeek));
        return next.plus(n - 1, ChronoUnit.WEEKS);
    };
}

Pass your TemporalAdjuster object to LocalDate.with. Get back another LocalDate with your desired result.

public static void main(String[] args) {
    LocalDate date = LocalDate.of(2017, 3, 7);
    date = date.with(nextNthDayOfWeek(2, DayOfWeek.MONDAY));
    System.out.println("date = " + date); // prints 2017-03-20
} 
于 2017-03-06T07:28:06.593 回答