Home Tutorial Java Core Java subtract months from date

 
 

Share on Google+Share on Google+
Java subtract months from date
Posted on: October 12, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java subtract months from date:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 12, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com