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?
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.
If you want the last second of the day, you can use: ZonedDateTime eod = zonedDateTime. with(LocalTime. of(23, 59, 59));
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With