LocalDate plusMonths() method in Java with Examples
The plusMonths() method of LocalDate class in Java is used to add the number of specified months in this LocalDate and return a copy of LocalDate.
This method adds the months field in the following steps:
- Add the months to the month-of-year field.
- Check if the date after adding months is valid or not.
- If date is invalid then method adjust the day-of-month to the last valid day.
For example, 2018-08-31 plus one month gives date 2018-09-31 but this is invalid result, so the last valid day of the month, 2018-09-30, is returned.This instance is immutable and unaffected by this method call.
public LocalDate plusMonths(long monthsToAdd)
Parameters: This method accepts a single parameter monthsToAdd which represents the months to add, may be negative.
Return Value: This method returns a LocalDate based on this date with the months added, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the plusMonths() method:
LocalDate before adding months: 2018-11-13 LocalDate after adding months: 2019-04-13
LocalDate before adding months: 2018-12-31 LocalDate after adding months: 2019-09-30