Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Subtract Year from Current Date in Java



In this article, we will learn to subtract a year from the current date using Java. We will be using the Calender class of java.util package.

Calendar class in Java is an abstract class that provides different methods to convert between a specific instant in time and a set of calendar fields such as HOUR, DAY_OF_MONTH, MONTH, YEAR, and so on. It is also used for manipulating the calender field.

Steps to subtract year from current date

Following are the steps to subtract year from current date ?

  • Import the Calendar class from the java.util package.
  • Create an instance of the Calendar class to represent the current date and time.
  • Display the current date and time using the calendar.getTime() method.
  • Subtract a specific number of years from the current date using the calendar.add() method with the Calendar.YEAR field and a negative value.
  • Display the updated date and time after subtracting the years.

Java program to subtract year from current date

The following is an example of subtracting the year from the current date ?

import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Subtract 20 Years
      calendar.add(Calendar.YEAR, -20);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}

Output

Current Date = Thu Nov 22 18:20:30 UTC 2018
Updated Date = Sun Nov 22 18:20:30 UTC 1998

Code Explanation

To subtract a year from the current date using Java, you first import the Calendar class from java.util package. We will create an instance of Calendar using Calendar.getInstance(), which initializes the object with the current date and time. The calendar.getTime() method is used to display the current date. To subtract a specific number of years, you use the calendar.add() method with the Calendar.YEAR field and a negative value, such as '-20', which subtracts 20 years from the current date. Finally, the updated date is displayed using calendar.getTime() to show the result after the subtraction.

Updated on: 2024-08-27T18:47:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements