Home Tutorial Java Core Add Years To Date

 
 

Share on Google+Share on Google+
Add Years To Date
Posted on: September 19, 2012 at 12:00 AM
Advertisement
This tutorial explains you how to add years to date.

Add Years To Date

This tutorial explains you how to add years to date.

Java provides an easy way of date time manipulation by Calendar class. Through this class, you can add or subtract date, month and year as per your requirement. The method add() adds or subtract values to the specified Calendar object. This calendar object is affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Example

import java.util.*;
import java.text.*;

public class AddYearsToDate {
 public static void main(String[] args) {
	 try{
      DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date d=(Date)formatter.parse("30-03-2012");
      Calendar cal=Calendar.getInstance();
      cal.setTime(d);
      cal.add(Calendar.YEAR, 4);	
      String newdate = formatter.format(cal.getTime());
      System.out.println("Today's Date: "+(formatter.format(d)));
      System.out.println("Date after 4 years: "+newdate);
	 }
	 catch(Exception e){}
}
}

Description of Code: In this example, we have created an instance of SimpleDateFormat class and specified the date format there. The date as string is then parsed through this formatter and stored into Date object. Then  set this date as Calendar time using setTime() method of Calendar class.

Output:

Today's Date: 30-03-2012
Date after 4 years: 30-03-2016

Advertisement

Related Tags for Add Years To 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: September 19, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com