There is no need to do any calculations manually.
You can adjust the set date using the knob using the LocalDateTime.with(adjuster) method. The next day of the week there is a built-in regulator: TemporalAdjusters.next(dayOfWeek) :
Returns the next weekday controller that adjusts the date before the first occurrence of the specified day of the week after the adjusted date.
public static void main(String[] args) { LocalDateTime dateTime = LocalDateTime.now(); LocalDateTime nextMonday = dateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)); System.out.println(nextMonday); }
This code will return next Monday depending on the current date.
Using static imports makes it easier to read code:
LocalDateTime nextMonday = dateTime.with(next(MONDAY));
Please note that if the current date is already on Monday, this code will return next Monday (i.e. Monday from next week). If you want to keep the current date in this case, you can use nextOrSame(dayOfWeek) .
Tunaki
source share