Handle invalid day-of-month
If the current LocalDate
instance has a day-of-month that is invalid for the new year, then withYear()
method adjusts the day-of-month value to the last valid day of the month. Add the following code below step 4.
LocalDate dateWithInvalidDayOfMonth = LocalDate.of(2021, 2, 31);
LocalDate newDateWithAdjustedDayOfMonth = dateWithInvalidDayOfMonth.withYear(2022);
System.out.println("Old Date: " + dateWithInvalidDayOfMonth + "\nNew Date: " + newDateWithAdjustedDayOfMonth);
Here, we set a date with an invalid day-of-month, 31st of February 2021 which doesn't exist. We then apply the withYear()
method to change the year to 2022. Since 2022 is not a leap year, and February has only 28 days, the day-of-month is adjusted to 28, which is the last valid day of February.