Menu

Java LocalDate plusYears() Method

Java LocalDate plusYears() Method

This method is used to plus the specified years to the local-date. It returns a copy of this LocalDate with the specified number of years added.

This method adds the specified years field in three steps:

  1. Add the input years to 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) plus one year would result in the invalid date 2009-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 plusYears(long yearsToAdd)

Parameters:

It takes a parameter of long type to specify the number of years.

Returns:

It returns a local date after adding the years.

Time for an Example:

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

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

Output:

2019-08-10 

New date : 2021-08-10

Time for another Example:

If after adding years, the date is invalid then the result will be the last valid day of the date. See, we added a year to a leap year that leads to an invalid date, so the compiler returned the last valid day of the 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.plusYears(1);
        System.out.println("New date : "+localDate);
    }
}

Output:

2012-02-29 

New date : 2013-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.of(2019, 8, 10);
        System.out.println(localDate);
        localDate = localDate.plusYears(10);
        System.out.println("New date : "+localDate);
    }
}