Java 8: Find nth DayOfWeek after specific day of month
Asked Answered
C

1

3

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?

Crumble answered 6/3, 2017 at 7:2 Comment(1)
Related: Get first next Monday after certain date?Jackfruit
B
6

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
} 
Basrhin answered 6/3, 2017 at 7:28 Comment(1)
Thank you very much for this nice solution!Crumble

© 2022 - 2024 — McMap. All rights reserved.