There is no 31st in February, but I was curious about what would happen if I added 1 month to 1/31 with plusMonths ()
.
According to Documentation
This method adds the specified amount to the month field in three steps.
First, add the months and check if there is a date corresponding to the added month. If there is no such date, it seems to return the last day of the month.
LocalDate date = LocalDate.of(2020,1,31);
System.out.println(date.plusMonths(1));
// 2020-02-29
LocalDate date = LocalDate.of(2020,1,30);
System.out.println(date.plusMonths(1));
// 2020-02-29
LocalDate date = LocalDate.of(2020,1,29);
System.out.println(date.plusMonths(1));
// 2020-02-29
LocalDate date = LocalDate.of(2020,1,28);
System.out.println(date.plusMonths(1));
// 2020-02-28
For dates that don't apply, you'll get a valid date back: clap:
What if minusMonths
is followed by plusMonths
?
LocalDate date = LocalDate.of(2020,1,31);
System.out.println(date.plusMonths(1).minusMonths(1));
// 2020-01-29
The result was 2020-01-29 because I did minusMonths
on 2020-02-29 and it became 2020-02-29 with plusMonths
.
Recommended Posts