获取一周中给定日期的下一个 LocalDateTime

Get the next LocalDateTime for a given day of week

我想在下一个(例如)星期一的 date/time 创建 LocalDateTime 的实例。

在Java时间API有什么方法吗,还是我应该计算当前日期和目标日期之间的天数,然后使用LocalDateTime.of()方法?

无需手工计算。

您可以使用方法 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);
}

此代码将 return 根据当前日期在下周一。

使用静态导入,使代码更易于阅读:

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

请注意,如果当前日期已经是星期一,则此代码将 return 下星期一(即下周的星期一)。如果你想在这种情况下保留当前日期,你可以使用 nextOrSame(dayOfWeek).