Search code examples
javadatetimedayofweeklocaldate

Java 8: Find nth DayOfWeek after specific day of month


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?


Solution

  • 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
    }