Opposite of subtracting years from a java date, this example will show how to add years to a date using Calendar.add, java 8 date time api, joda DateTime.plusYears and apache common DateUtils.addYears. A couple of years after Packers won superbowl XLV, the San Francisco 49ers handed the packers a wippin. The examples below represents the dates by adding years to the superbowl date.
Straight up Java
@Test
public void add_years_to_date_in_java () {
Calendar superBowlXLV = Calendar.getInstance();
superBowlXLV.set(2011, 1, 6, 0, 0);
Calendar fortyNinersSuck = Calendar.getInstance();
fortyNinersSuck.setTimeInMillis(superBowlXLV.getTimeInMillis());
fortyNinersSuck.add(Calendar.YEAR, 2);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
logger.info(dateFormatter.format(superBowlXLV.getTime()));
logger.info(dateFormatter.format(fortyNinersSuck.getTime()));
assertTrue(fortyNinersSuck.after(superBowlXLV));
}
Output
02/06/2011 00:00:08 CST
02/06/2013 00:00:08 CST
Java 8 Date and Time API
Java 8 LocalDateTime.plusYears will return a copy of the LocalDateTime with the specified number of years added.
@Test
public void add_years_to_date_in_java8() {
LocalDateTime superBowlXLV = LocalDateTime.of(2011, Month.FEBRUARY, 6,
0, 0);
LocalDateTime fortyNinersSuck = superBowlXLV.plusYears(2);
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(superBowlXLV.format(formatter));
logger.info(fortyNinersSuck.format(formatter));
assertTrue(fortyNinersSuck.isAfter(superBowlXLV));
}
Output
02/06/2011 00:00:00 0
02/06/2013 00:00:00 0
Joda Time
Joda DateTime.plusYears will return a copy the DateTime plus the specified number of years.
@Test
public void add_years_to_date_in_java_joda () {
DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
DateTime fortyNinersSuck = superBowlXLV.plusYears(2);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
logger.info(superBowlXLV.toString(fmt));
logger.info(fortyNinersSuck.toString(fmt));
assertTrue(fortyNinersSuck.isAfter(superBowlXLV));
}
Output
02/06/2011 00:00:08 CST
02/06/2013 00:00:08 CST
Apache Commons
Apache commons DateUtils.addYears will adds a number of years to the date returning a new object.
@Test
public void add_years_to_date_in_java_apachecommons () {
Calendar superBowlXLV = Calendar.getInstance();
superBowlXLV.set(2011, 1, 6, 0, 0);
Date fortyNinersSuck = DateUtils.addYears(superBowlXLV.getTime(), 2);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
logger.info(dateFormatter.format(superBowlXLV.getTime()));
logger.info(dateFormatter.format(fortyNinersSuck));
assertTrue(fortyNinersSuck.after(superBowlXLV.getTime()));
}
Output
02/06/2011 00:00:00 CST
02/06/2013 00:00:00 CST