Home Tutorial Java Core Java subtract years from date

 
 

Share on Google+Share on Google+
Java subtract years from date
Posted on: October 12, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to subtract years from date.

Java subtract years from date

In this tutorial, you will learn how to subtract years 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 years 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 years from the calendar and using the Date class, we have got the date of that day.

Example:

import java.util.*;

public class SubtractYearsFromDate{

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

Output:

Today's Date: Fri Oct 12 13:00:31 IST 2012
Date after 4 years: Sun Oct 12 13:00:31 IST 2008
Advertisement

Related Tags for Java subtract years 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