Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the next LocalDateTime for a given day of week

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

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

like image 939
graczun Avatar asked Feb 12 '16 14:02

graczun


People also ask

How do I get the day of the week from LocalDateTime?

The getDayOfWeek() method of an LocalDateTime class is used to return the day-of-week field, which is an enum DayOfWeek. This method returns the enum DayOfWeek for the day-of-week.

How do I get end of the day from ZonedDateTime?

If you want the last second of the day, you can use: ZonedDateTime eod = zonedDateTime. with(LocalTime. of(23, 59, 59));

How do I get LocalTime LocalDateTime?

You can use the method toLocalDate() to convert a LocalDateTime object to LocalDate in Java 8 and toLocalTime() to get a LocalTime instance from the LocalDateTime object. LocalDate retrievedDate = fromDateAndTime. toLocalDate(); LocalTime retrievedTime = fromDateAndTime.

How do I add a one day to LocalDate?

The plusDays() method of a LocalDate class in Java is used to add the number of specified day in this LocalDate and return a copy of LocalDate. For example, 2018-12-31 plus one day would result in 2019-01-01. This instance is immutable and unaffected by this method call.


1 Answers

There is no need to do any calculations by hand.

You can adjust a given date with an adjuster with the method LocalDateTime.with(adjuster). There is a built-in adjuster for the next day of the week: TemporalAdjusters.next(dayOfWeek):

Returns the next day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week after the date being adjusted.

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 the next monday based on the current date.

Using static imports, this makes the code easier to read:

LocalDateTime nextMonday = dateTime.with(next(MONDAY));

Do note that if the current date is already on a monday, this code will return the next monday (i.e. the monday from the next week). If you want to keep the current date in that case, you can use nextOrSame(dayOfWeek).

like image 59
Tunaki Avatar answered Oct 12 '22 23:10

Tunaki