获取一周中给定日期的下一个LocalDateTime [英] Get the next LocalDateTime for a given day of week

查看:640
本文介绍了获取一周中给定日期的下一个LocalDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下一个星期一(例如)星期一的日期/时间创建LocalDateTime的实例.

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

Java Time API中是否有任何方法,还是应该计算当前日期和目标日期之间有多少天,然后使用LocalDateTime.of()方法?

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?

推荐答案

无需手动进行任何计算.

There is no need to do any calculations by hand.

您可以使用调节器通过 TemporalAdjusters.next(dayOfWeek) :

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

这篇关于获取一周中给定日期的下一个LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆