Java Program To Add Years To Date
Chapter:
Interview Programs
Last Updated:
23-05-2016 20:12:10 UTC
Program:
/* ............... START ............... */
import java.util.Calendar;
import java.util.GregorianCalendar;
public class JavaAddYearsToDateExample {
public static java.sql.Date addYears(final java.util.Date date, final int years) {
java.sql.Date calculatedDate = null;
if (date != null) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.YEAR, years);
calculatedDate = new java.sql.Date(calendar.getTime().getTime());
}
return calculatedDate;
}
public static void main(String[] args) {
final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis());
System.out.println("Current Date : " + currentDate);
// Note: the input is a negative number, hence substracts the num of
// years from the input date
final int yearsToAdd = -5;
final java.sql.Date calculatedDate = addYears(currentDate, yearsToAdd);
System.out.println("Date after adding years : " + calculatedDate);
}
}
/* ............... END ............... */
Output
Current Date : Mon May 23 23:53:28 IST 2016
Date after adding years : 2011-05-23
Tags
Java Program To Add Years To Date, Java, Interview Programs