Introduction
In this lab, you will learn how to use the minusYears()
method from the LocalDate class in Java to subtract years from a given date. This method allows you to perform date arithmetic with ease in your Java programs.
In this lab, you will learn how to use the minusYears()
method from the LocalDate class in Java to subtract years from a given date. This method allows you to perform date arithmetic with ease in your Java programs.
Add the following line of code at the beginning of the program to import the LocalDate class, which is used to represent a date (year, month, and day):
import java.time.LocalDate;
Create a LocalDate
object representing a date by calling the of()
method of the LocalDate class. The of()
method takes three arguments: year, month, and day. In this example, we are creating a LocalDate
object for October 10th, 2009.
LocalDate localDate = LocalDate.of(2009, 10, 10);
Use the minusYears()
method to subtract years from the date represented by the LocalDate
object. The minusYears()
method takes a single argument, which is the number of years to subtract.
localDate = localDate.minusYears(1);
Output the resulting date after subtracting the years from the LocalDate
object using the println()
method.
System.out.println("New date : "+localDate);
Sometimes, subtracting years from a LocalDate
object can lead to an invalid date. For example, subtracting a year from February 29th during a leap year can result in an invalid date of February 29th in a standard year.
The minusYears()
method handles invalid dates by adjusting the resulting date to the last valid day of the month. For example, if the resulting date is February 29th and the year is not a leap year, the resulting date is adjusted to February 28th.
LocalDate localDate = LocalDate.of(2012, 02, 29);
System.out.println(localDate);
localDate = localDate.minusYears(1);
System.out.println("New date : "+localDate);
Save the program file and navigate to the directory where the file is saved in the terminal. Compile and run the program using the following commands:
javac DateDemo.java
java DateDemo
In this lab, you learned how to use the minusYears()
method from the LocalDate
class in Java to subtract years from a date. This method is simple to use and handles invalid dates by adjusting the resulting date to the last valid day of the month.