我正在尝试获取包含月号,月中星期几和星期几的日期我认为这很容易,并且做到了:
LocalDate nextbookingDate = LocalDate.now().plusYears(1);
nextBookingDate = nextBookingDate.with(Month.of(1));
nextBookingDate = nextBookingDate.with(WeekFields.ISO.weekOfMonth(), 1);
nextBookingDate = nextBookingDate.with(DayOfWeek.of(1));
System.out.println(nextBookingDate); //2019-12-30
nextBookingDate
应该为2020-01-06,因为它是一月的第一个星期一。但是为什么我会得到2019-12-30以及如何解决呢?
我尚不清楚您通常想要什么结果,为什么。如果我假设您希望下一个日期是某个月的某天的第[n天,那么它比您的代码要复杂一些。 编辑: NorthernSky在the comment under his/her answer中是正确的,即.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY))
更直接,更简短地为我们提供了我们所需要的东西。这应该工作:
ZoneId zone = ZoneId.of("Africa/Bamako");
LocalDate today = LocalDate.now(zone);
LocalDate nextBookingDate = today.with(Month.JANUARY)
.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY));
if (nextBookingDate.isBefore(today)) {
// Take next year instead
nextBookingDate = today.plusYears(1)
.with(Month.JANUARY)
.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.MONDAY));
}
System.out.println("Next booking date: " + nextBookingDate);
我刚运行代码时的输出是:Documentation of下一次预订日期:2020-01-06
TemporalAdjusters.dayOfWeekInMonth()
将为我们提供每月的第一个星期一,第三个星期二,等等。因此,请在一周中的任何一天以及最多4或5个数字中输入此方法。请提供您想要的非洲/巴马科放置所在的时区,因为它在所有时区中都不是同一日期。
链接:
TemporalAdjusters.dayOfWeekInMonth()
。TemporalAdjusters.dayOfWeekInMonth()
但请注意,2019年12月30日实际上是2020年第1周的第一天。因为问题已更新,所以更相关的答案是:
nextBookingDate = now() .with(Month.of(1)) .with(WeekFields.ISO.weekOfMonth(), 1) .with(DayOfWeek.of(1));
并且您可以使用2到5之间的数字适当地替换1作为dayOfWeekInMonth的参数。