Subtract days from current date using Calendar.DATE in Java

Java 8Object Oriented ProgrammingProgramming

Import the following package for Calendar class in Java.

import java.util.Calendar;

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

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

Now, let us subtract the days using the add() method and Calendar.DATE constant. Set a negative value here since we are decrementing.

calendar.add(Calendar.DATE, -2);

Example

 Live Demo

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

Output

Current Date = Thu Nov 22 16:09:20 UTC 2018
Updated Date = Tue Nov 20 16:09:20 UTC 2018
raja
Published on 06-Dec-2018 07:21:27
Advertisements