javadatejava-8

LocalDate.plusMonth giving incorrect result for February


I am trying to to use plusMonths API from java.time.LocalDate. Going through the java doc, its clear that the dates are adjusted for any invalid exceed of the dates.

For e.g 31-03-2017 + 1 Month = 31-04-2017--> 30-04-2017(as 31 April is invalid).

However, when I try to use the API for the February dates, it doesn't return the last day of next month(e.g March), instead returns the date after adding 30 days.

For e.g 28-02-2017 + 1 Month = 29-03-2017(expected 31-03-2017).

public class AddMonthTest {
    public static void main(String[] args) {            
        System.out.println(LocalDate.of(2017, 02, 28).plusMonths(1));       
}

Gives output : 2017-03-28 where as expectation that it should return 31-03-2017.


Solution

  • You might use TemporalAdjusters.lastDayOfMonth() move to the last day of month

    public static void main(String[] args) {
        System.out.println(LocalDate.of(2017, 2, 28).plusMonths(1).with(TemporalAdjusters.lastDayOfMonth()));
    }