Introduction
The plusYears()
method in Java is used to add a certain number of years to the specified LocalDate
object and returns a copy of the date object with the years added.
The plusYears()
method in Java is used to add a certain number of years to the specified LocalDate
object and returns a copy of the date object with the years added.
To get started with Java programming, you need to have the Java Development Kit (JDK) installed on your local machine. To check if you already have it installed, run the following command:
java -version
If you don't have the JDK installed, you can download it from the official Java website and follow the installation instructions.
Create a Java class file named LocalDateDemo.java
in the ~/project
directory using any text editor of your choice.
touch ~/project/LocalDateDemo.java
To use the LocalDate
class and its methods, you need to import the java.time.LocalDate
package.
import java.time.LocalDate;
LocalDate
objectCreate a LocalDate
object using the of()
method of the class and set the date.
LocalDate date = LocalDate.of(2021, 10, 01);
plusYears()
method to add years to the dateUse the plusYears()
method to add a certain number of years to the date object. In this example, we are adding 2 years to the date.
LocalDate newDate = date.plusYears(2);
In the end, print the original LocalDate object and the new LocalDate object after adding years. Use the toString()
method to convert the date object to a string for display purposes.
System.out.println("Original Date: " + date.toString());
System.out.println("New Date: " + newDate.toString());
Now, create a LocalDate
object for a leap year, and try to add 1 year to it using the plusYears()
method.
LocalDate leapDate = LocalDate.of(2020, 02, 29);
LocalDate leapNewDate = leapDate.plusYears(1);
In the end, print the original leap year date object and the new leap year object after adding years. As the result date is invalid, the plusYears()
method adjusts it to the last valid date of the month, i.e., February 28.
System.out.println("Original Leap Date: " + leapDate.toString());
System.out.println("New Leap Date: " + leapNewDate.toString());
Compile the LocalDateDemo.java
file using the following command:
javac LocalDateDemo.java
Run the program using the following command:
java LocalDateDemo
The plusYears()
method in Java is used to add a certain number of years to a LocalDate
object and return a new date object with the years added. The method adjusts the date object if the resulting date would be invalid. This lab demonstrated how to use the plusYears()
method to add years to a LocalDate
object and how to handle leap year date objects using the method.