Day-of-Week Adjusters: next and previous
You'll learn how to navigate to specific days of the week using nextOrSame, next, previousOrSame, and previous adjusters.
Understanding Day-of-Week Navigation
Sometimes you need to find "the next Monday" or "the previous Friday" from a given date. The TemporalAdjusters class provides four convenient methods for jumping to specific days of the week:
next(DayOfWeek)– finds the next occurrence of the specified day (always moves forward at least one week if already on that day)nextOrSame(DayOfWeek)– finds the next occurrence, or returns the same date if it's already that dayprevious(DayOfWeek)– finds the previous occurrence (always moves backward)previousOrSame(DayOfWeek)– finds the previous occurrence, or returns the same date if already on that day
Think of it like a calendar where you're looking forward or backward to land on a specific weekday.
Examples
LocalDate today = LocalDate.of(2024, 1, 15); // Monday
System.out.println(today.getDayOfWeek()); // MONDAY
// Jump to next Friday
LocalDate nextFri = today.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
System.out.println(nextFri); // 2024-01-19
// Next Monday (skips current Monday)
LocalDate nextMon = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println(nextMon); // 2024-01-22
// Next or same Monday (returns today)
LocalDate sameOrNext = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
System.out.println(sameOrNext); // 2024-01-15
// Previous Wednesday
LocalDate prevWed = today.with(TemporalAdjusters.previous(DayOfWeek.WEDNESDAY));
System.out.println(prevWed); // 2024-01-10
These adjusters work with any temporal object that supports day-of-week fields, including LocalDate, LocalDateTime, and ZonedDateTime.
Key Takeaway: Use next(), nextOrSame(), previous(), and previousOrSame() from TemporalAdjusters to navigate to specific days of the week, with control over whether the current day counts as a match.