Java – find the next occurrence of the day of the week in jsr-310
Given a jsr-310 object, such as localdate, how can I find the date of the next Wednesday (or any other day of the week)?
LocalDate today = LocalDate.Now(); LocalDate nextWed = ???
Solution
The answer depends on your definition of "next Wednesday; -)
JSR - 310 provides two options for using the temporaladjusters class
The first option is next ():
LocalDate input = LocalDate.Now(); LocalDate nextWed = input.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
The second option is nextorsame():
LocalDate input = LocalDate.Now(); LocalDate nextWed = input.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));
The two are different according to the day of the week of the input date
If the input date is January 22, 2014 (Wednesday), then:
>Next () will return to 2014-01-29 in a week > nextorsame () will return to 2014-01-22, the same as the input
If the input date is January 20, 2014 (Monday), then:
>Next() will return to 2014-01-22 > nextorsame() will return to 2014-01-22
Namely Next () always returns a later date, while nextorsame () returns the input date if it matches
Note that both options look better than static import:
LocalDate nextWed1 = input.with(next(WEDNESDAY)); LocalDate nextWed2 = input.with(nextOrSame(WEDNESDAY));
Temporaladjusters also includes matching previous () and previousorsame () methods