LocalDate minusYears() method in Java with Examples
The minusYears() method of a LocalDate class is used to subtract the number of specified years from this LocalDate and return a copy of LocalDate.
This method subtracts the years field in the following steps:
- Firstly, it subtracts the years from the year field in this LocalDate.
- Check if the date after subtracting years is valid or not.
- If the date is invalid then method adjusts the day-of-month to the last valid day.
For example, 2016-02-29 (leap year) minus one year gives date 2015-02-29 but this is an invalid result, so the last valid day of the month, 2015-02-28, is returned. This instance is immutable and unaffected by this method call.
public LocalDate minusYears(long yearsToSubtract)
Parameters: This method accepts a single parameter yearsToSubtract which represents the years to subtract, may be negative.
Return Value: This method returns a LocalDate based on this date with the years subtracted, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the minusYears() method:
LocalDate before subtracting years:2020-10-22 LocalDate after subtracting years:1990-10-22
LocalDate before subtracting years: 2020-02-29 LocalDate after subtracting years: 2041-02-28
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.