Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Mahbub Rahman Avatar asked Jan 18 '26 02:01

Mahbub Rahman


1 Answers

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
} 
like image 100
JB Nizet Avatar answered Jan 20 '26 15:01

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!