问题
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?
回答1:
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).
来源:https://stackoverflow.com/questions/35365571/get-the-next-localdatetime-for-a-given-day-of-week