我在我的应用程序中使用此代码:
final DateTime selectedDate = new DateTime().withMonthOfYear(month).withDayOfMonth(day).withYear(year);
其中
month
= 2, day
= 29, year
= 2024
我得到这个例外:
Value 29 for dayOfMonth must be in the range [1,28]
但是2024年是闰年。 有人对此有解决方案吗?
虽然您的表达式的最终值似乎是一个有效日期,但您已经按照需要在整个过程中评估无效日期的顺序对其进行评估。
你写的
final DateTime selectedDate =
new DateTime().withMonthOfYear(month).withDayOfMonth(day).withYear(year);
从左到右计算。因此它等同于
DateTime result1 = new DateTime().withMonthOfYear(month);
DateTime result2 = result1.withDayOfMonth(day);
final DateTime selectedDate = result2.withYear(year);
现在,假设我今天(2023 年 3 月 20 日)按照您指定的
month = 2, day = 29, year = 2024
运行此程序。那我有
DateTime result1 = 20 February 2023 // all good so far
DateTime result2 = 29 February 2023 // whoops!
这就是抛出异常的地方。我们从来没有把年份定为 2024 年。
重新安排您的代码以便首先调用
withYear
将解决此问题,因为所有中间结果都是有效日期。
final DateTime selectedDate =
new DateTime().withYear(year).withMonthOfYear(month).withDayOfMonth(day);
更好的主意是Ole的主意
final DateTime selectedDate = new DateTime().withDate(year, month, day);
在一次调用中设置所有三个字段,因此您无需担心中间结果。
但最好的办法是让您使用
java.time
包中的类,而不是 Joda。 Joda 已经过时将近 10 年了。
import java.time.LocalDate;
// ...
final LocalDate selectedDate = LocalDate.of(year, month, day);