Java 8: Find nth DayOfWeek after specific day of month

放肆的年华 提交于 2021-02-08 03:36:32

问题


In Java 8, what I found is

TemporalAdjuster temporal = dayOfWeekInMonth(1,DayOfWeek.MONDAY) 

gives the temporal for the first Monday of a month, and

next(DayOfWeek.MONDAY)

gives the next Monday after a specific date.

But I want to find nth MONDAY after specific date.

For example, I want 2nd MONDAY after 2017-06-06 and it should be 2017-06-19 where

dayOfWeekInMonth(2,DayOfWeek.MONDAY)

will give me 2017-06-12 and

next(DayOfWeek.MONDAY) 

has of course no parameter for the nth DayOfWeek's indicator. It will give the next first MONDAY which is 2017-06-12.

How I can calculate it without looping?


回答1:


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
} 


来源:https://stackoverflow.com/questions/42619409/java-8-find-nth-dayofweek-after-specific-day-of-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!