TemporalAdjusters.next(DayOfWeek)
and TemporalAdjusters.nextOrSame(DayOfWeek)
are part of java.time.temporal.TemporalAdjusters
class in Java. They adjust the date to the next, or the first occurrence of the specified DayOfWeek
, or stay at the same date if it’s the desired DayOfWeek
.
Here is how to use these methods:
package org.kodejava.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class NextOrSameExample {
public static void main(String[] args) {
// Get the current date
LocalDate date = LocalDate.now();
System.out.println("Current date: " + date);
LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday: " + nextMonday);
LocalDate nextOrSameFriday = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
System.out.println("Next Friday or same day if it's Friday: " + nextOrSameFriday);
}
}
Output:
Current date: 2024-01-18
Next Monday: 2024-01-22
Next Friday or same day if it's Friday: 2024-01-19
In the above example:
LocalDate.now()
is used to get the current date..with(TemporalAdjusters.next(DayOfWeek.MONDAY))
adjusts the date to the next Monday..with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY))
adjusts the date to the next Friday or stays at the same date if it’s already Friday.