Get the next LocalDateTime for a given day of week

℡╲_俬逩灬. 提交于 2020-05-23 06:01:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!