Get the next LocalDateTime for this day of the week

I want to create an instance of LocalDateTime on the date / time of the next (for example) Monday.

Is there any method in the Java Time API, or should I do the calculation of how many days are between current and ending dates, and then use the LocalDateTime.of () method?

+7
java java-8 jodatime java-time
source share
1 answer

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) .

+12
source share

All Articles