Subtract Months from Current Date Using Calendar Add Method in Java



When working with dates in Java, it's common to need to increment or decrement months. The Calendar class makes it easy to manipulate dates. This article shows how to decrement the current date by a specified number of months using the Calendar class.

Problem Statement

Given a Java program to decrement the current date by a specified number of months using the Calendar class.

Output

Current Date = Thu Nov 22 16:37:42 UTC 2018
Updated Date = Thu Mar 22 16:37:42 UTC 2018

Basic Approach

Below are the steps to subtract months from current date using Calendar.add() method

  • Step 1. Import the java.util.Calendar package.
  • Step 2. Create a Calendar object using the getInstance() method to get the current date and time.
  • Step 3. Display the current date and time using the getTime() method.
  • Step 4. Use the add() method of the Calendar class to decrement the months. Pass Calendar.MONTH as the first argument and a negative value (representing the number of months to decrement) as the second argument.
  • Step 5. Display the updated date and time after decrementing the months.

Example

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 8 months from current date
        calendar.add(Calendar.MONTH, -8);
        System.out.println("Updated Date = " + calendar.getTime());
    }
}

Output

Current Date = Thu Nov 22 16:37:42 UTC 2018
Updated Date = Thu Mar 22 16:37:42 UTC 2018

Code Explanation

Import the following package for Calendar class in Java.

import java.util.Calendar;

Firstly, create a Calendar object and display the current date and time.

Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());

Now, let us decrement the months using the calendar.add() method and Calendar.MONTH constant. Set a negative value since we are decrementing.

calendar.add(Calendar.MONTH, -10);
Updated on: 2024-07-08T18:03:44+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements