I use this code in my application:
final DateTime selectedDate = new DateTime().withMonthOfYear(month).withDayOfMonth(day).withYear(year);
where month = 2, day = 29, year = 2024
and I get this exception:
Value 29 for dayOfMonth must be in the range [1,28]
but 2024 is a leap year. Does anyone have a solution about this?
Whereas the final value of your expression appears to be a valid date, you've evaluated it in an order which requires an invalid date to be evaluated along the way.
You wrote
which is evaluated from left to right. It's therefore equivalent to
Now, suppose I run this today (20 March 2023) with
month = 2, day = 29, year = 2024as you specified. Then I haveand this is the point where your exception is thrown. We never got as far as setting the year to 2024.
Rearranging your code so that
withYeargets called first would fix this, because all the intermediate results would be valid dates.A better idea is Ole's idea
which sets all three fields in a single call, so you don't need to be concerned about intermediate results.
But the best idea of all would be for you to use the classes in the
java.timepackage, instead of Joda. Joda has been obsolete for almost 10 years now.