Menu

Java LocalDate minusYears() Method

Java LocalDate minusYears() Method

Java minusYears() method is used to subtract the specified years from the local-date. It returns a copy of this LocalDate with the specified number of years subtracted.

This method subtracts the specified years field in three steps:

  1. Subtract the input years from the year field
  2. Check if the resulting date would be invalid
  3. Adjust the day-of-month to the last valid day if necessary

For example, 2008-02-29 (leap year) minus one year would result in the invalid date 2007-02-29 (standard year). Instead of returning an invalid result, the last valid day of the month, 2007-02-28, is selected instead.

Syntax

public LocalDate minusYears(long yearsToSubtract)

Parameters:

It takes a prameter of long type to specify the amount of years.

Returns:

It returns a local date after subtracting the years.

Time for an Example:

Here, in this example, we are subtracting a year from the local-date. The minusYear() method returns a new date after subtracting the specified years. See the example below.

import java.time.LocalDate; 
public class DateDemo {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.of(2009, 10, 10);
        System.out.println(localDate);
        localDate = localDate.minusYears(1);
        System.out.println("New date : "+localDate);
    }
}

Output:

2009-10-10 

New date : 2008-10-10

Time for another Example:

If after subtracting years, date is invalid then the result will be last valid day of the date. See, we subtracted a year from a leap year that lead to invalid date, so the compiler returned the last vaid day of date.

import java.time.LocalDate; 
public class DateDemo {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.of(2012, 02, 29);
        System.out.println(localDate);
        localDate = localDate.minusYears(1);
        System.out.println("New date : "+localDate);
    }
}

Output:

2012-02-29 

New date : 2011-02-28

Live Example:

Try with a live example, execute the code instantly with our powerful Online Java Compiler.

import java.time.LocalDate; 
public class Main {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.now();
        localDate = localDate.minusYears(10);
        System.out.println("New date : "+localDate);
    }
}