Add days to date

Opposite of subtracting days from date in java, this example demonstrates how to add days to a date using java Calendar.add, java 8 date time api, joda DateTime.plusDays and apache commons DateUtils.addDays. Since the Green Bay Packers won super bowl XLV against the Pittsburgh Steelers on February 6, 2011 we will add one day simulating the celebration date.

Straight up Java

@Test
public void add_days_to_date_in_java () {

    Calendar superBowlXLV = Calendar.getInstance();
    superBowlXLV.set(2011, 1, 6, 0, 0);

    Calendar celebration = Calendar.getInstance();
    celebration.setTimeInMillis(superBowlXLV.getTimeInMillis());
    celebration.add(Calendar.DATE, 1);

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

    logger.info(dateFormatter.format(superBowlXLV.getTime()));
    logger.info(dateFormatter.format(celebration.getTime()));

    assertTrue(celebration.after(superBowlXLV));
}

Output

02/06/2011 00:00:50 CST
02/07/2011 00:00:50 CST

Java 8 Date and Time API

Java 8 LocalDateTime.plusDays will return a copy of the LocalDateTime with the specified number of days added.

@Test
public void add_days_to_date_in_java8() {

    LocalDateTime superBowlXLV = LocalDateTime.of(2011, Month.FEBRUARY, 6,
            0, 0);
    LocalDateTime celebration = superBowlXLV.plusDays(1);

    java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
            .ofPattern("MM/dd/yyyy HH:mm:ss S");

    logger.info(superBowlXLV.format(formatter));
    logger.info(celebration.format(formatter));

    assertTrue(celebration.isAfter(superBowlXLV));
}

Output

02/06/2011 00:00:00 0
02/07/2011 00:00:00 0

Joda Time

Joda DateTime.plusDays will return a copy the DateTime plus the specified number of days.

@Test
public void add_days_to_date_in_java_with_joda () {

    DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
    DateTime celebration = superBowlXLV.plusDays(1);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");

    logger.info(superBowlXLV.toString(fmt));
    logger.info(celebration.toString(fmt));

    assertTrue(celebration.isAfter(superBowlXLV));
}

Output

02/06/2011 00:00:00 CST
02/07/2011 00:00:00 CST

Apache Commons

Apache commons DateUtils.addDays will adds a number of days to the date returning a new object.

@Test
public void add_days_to_date_in_java_with_apachecommons () {

    Calendar superBowlXLV = Calendar.getInstance();
    superBowlXLV.set(2011, 1, 6, 0, 0);

    Date celebration = DateUtils.addDays(superBowlXLV.getTime(), 1);

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

    logger.info(dateFormatter.format(superBowlXLV.getTime()));
    logger.info(dateFormatter.format(celebration));

    assertTrue(celebration.after(superBowlXLV.getTime()));
}

Output

02/06/2011 00:00:59 CST
02/07/2011 00:00:59 CST