Java subtract months from date


 

Java subtract months from date

In this tutorial, you will learn how to subtract months from date.

In this tutorial, you will learn how to subtract months from date.

Java subtract months from date

In this tutorial, you will learn how to subtract months from date.

Using the Calendar class, you can add and subtract date with the add() method. To subtract date, value should be passed with negative(-). This will reduce date from date. Here, we are going to subtract few months from current date and return the date of that day. For this, we have created a calendar instance and get a date to represent the current date. Then using the method add() of Calendar class, we have subtracted 4 months from the calendar and using the Date class, we have got the date of that day.

Example:

import java.util.*;

public class SubtractMonthsFromDate{

  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    Date today = calendar.getTime();
    System.out.println("Today's Date: " + today);
    calendar.add(Calendar.MONTH, -4);
    Date dateMonths = calendar.getTime();
    System.out.println("Date before 4 months: " + dateMonths);
  }
}

Output:

Today's Date: Fri Oct 12 12:59:59 IST 2012
Date after 4 months: Tue Jun 12 12:59:59 IST 2012

Ads