How To Subtract Days to Date in Java

In this tutorial, we will be going to solve the problem on how to subtract Days to date in Java.

Also, we will be looking at which methods are necessary for doing this task and the successful completion of the above problem.

Subtract Days to Date in Java

Initially, we have imported the Calendar class for the purpose of taking the system input of date.

This class comes with various methods for purposes such as, getting the value of the calendar field and so on.

Inside the main method, we created an object for the above class and called the method getInstance, which thereafter returns a signature object.

After the above object creation, we called the method getTime(), which gives the system a date object representing the calendar’s time value.

We displayed the current date with the above method’s help.

Now with the help of the Calendar class’s object, we will be invoking the add method in Java, for the subtraction of days.

This may be a doubtful situation as to how the add method will be helpful in subtracting days in Java.

This is possible because of the trick that in the position of adding a particular number in add method, we will be passing a negative value of the number of days we want to remove.

By this trick, we can easily get our result for the above problem.

Now, since we have got the updated value with subtracted days in from the date, we can now display the above result with the getTime method.

You may also read:

How To Add days to Date in Java

Java program Subtract Days to Date

Below is the Program for the java problem on how to subtract days to date:

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

After the successful compilation of the above code, we will be getting our required result, which is subtracted days from a date.

Below is sample output for the above program:

How To Subtract Days to Date in Java

Leave a Reply

Your email address will not be published. Required fields are marked *