Java LocalDate Class | plusYears() Method with Example

LocalDate Class plusYears() method: Here, we are going to learn about the plusYears() method of LocalDate Class with its syntax and example.
Submitted by Preeti Jain, on June 01, 2020

LocalDate Class plusYears() method

  • plusYears() method is available in java.time package.
  • plusYears() method is used to add the given duration in years to this LocalDate and return the LocalDate.
  • plusYears() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • plusYears() method may throw an exception at the time of performing addition.
    DateTimeException: This exception may throw when the calculated results exceed the length of this LocalDate.

Syntax:

    public LocalDate plusYears(long yrs_val);

Parameter(s):

  • long yrs_val – represents the years value to add to this LocalDate.

Return value:

The return type of this method is LocalDate, it returns the LocalDate that holds the value added the given years to this LocalDate.

Example:

// Java program to demonstrate the example 
// of plusYears(long yrs_val) method of LocalDate

import java.time.*;

public class PlusYearsOfLocalDate {
    public static void main(String args[]) {
        long years = 3;
        // Instantiates two LocalDate
        LocalDate l_da1 = LocalDate.parse("2007-04-04");
        LocalDate l_da2 = LocalDate.of(2008, Month.FEBRUARY, 06);

        // Display l_da1,l_da2 and years
        System.out.println("LocalDate l_da1,l_da2 : ");
        System.out.println("l_da1: " + l_da1);
        System.out.println("l_da2: " + l_da2);
        System.out.println("years to add: " + years);

        System.out.println();

        // Here, this method adds the
        // given years to this date l_da1
        // i.e. here we are adding 3
        // years to the date l_da1
        LocalDate plus_yrs = l_da1.plusYears(years);

        // Display plus_yrs
        System.out.println("l_da1.plusYears(years): " + plus_yrs);

        // Here, this method adds the
        // given years to this date l_da2
        // i.e. here we are adding 3
        // years to the date l_da2
        plus_yrs = l_da2.plusYears(years);

        // Display plus_yrs
        System.out.println("l_da2.plusYears(years): " + plus_yrs);
    }
}

Output

LocalDate l_da1,l_da2 : 
l_da1: 2007-04-04
l_da2: 2008-02-06
years to add: 3

l_da1.plusYears(years): 2010-04-04
l_da2.plusYears(years): 2011-02-06



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.