To subtract years from the date, you can use minusYears() method of the LocalDate class of Java 8.
This method returns a copy of the date after subtracting the specified years.
For example, if you subtract 20 years from the date "2022-03-14" then the result will be 2002-03-14.
You can use this method to minus years such as 1 year, 2 years, 5 years, 10 years, etc.
Let's understand with the running examples.
/*
* Code example to subtract years from date in Java
*/
import java.time.LocalDate;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2022-03-14";
// parse the date into date time
LocalDate date = LocalDate.parse(strDate);
// Displaying time
System.out.println("Date : "+date);
// Minus year more than max
date = date.minusYears(20);
// Displaying time
System.out.println("New date : "+date);
}
}
Output:
Date : 2022-03-14
New date : 2002-03-14
Now, let's have a look at this method signature:
public LocalDate minusYears(long yearsToSubtract)
Package Name: java.time;
Class Name: LocalDate
Return Value: It returns a copy of localdate after subtracting the specified years, not null.
Parameters: It takes a single long type value. It may be negative.
Exceptions: It throws a DateTimeException if the result exceeds the supported(either MIN or MAX) date range.
Version: Since 1.8
Let's see more examples.
To subtract years from the current date, we first used the now() method to get the current date and then used the minusYears() method.
/*
* Code example to subtract years from current date in Java
*/
import java.time.LocalDate;
public class JExercise {
public static void main(String[] args) {
// Current date
LocalDate date = LocalDate.now();
// Displaying time
System.out.println("Date : "+date);
// Minus year more than max
date = date.minusYears(15);
// Displaying time
System.out.println("New date : "+date);
}
}
Output:
Date : 2022-03-25
New date : 2007-03-25
The minusYears() method accepts the negative value as an argument as well. This method performs the just opposite with the negative input.
It means it adds the years rather than subtracts the years. See the below Java code.
/*
* Code example to add years from local date in Java
*/
import java.time.LocalDate;
public class JExercise {
public static void main(String[] args) {
// Current date
LocalDate date = LocalDate.now();
// Displaying time
System.out.println("Date : "+date);
// Minus year more than max
date = date.minusYears(-15); // negative year
// Displaying time
System.out.println("New date : "+date);
}
}
Output:
Date : 2022-03-25
New date : 2037-03-25
Use this code to get results in a single line of code. If you are a beginner, skip this code.
LocalDate.now().minusYears(5);
This code will return a localdate object after subtracting 5 years from the current date. You just replace the value with your input and get the result instantly.