Add hours to date

Opposite of subtracting hours from a java date, this example will demonstrates how to add hours to date using Calendar.add, java 8 date time api, joda LocalDateTime.plusHours and apache commons DateUtils.addHours. In the examples below, we will set a date that represents new years eve, December 31st, then adding one hour to return a date representing new years day or January 1st.

Straight up Java

@Test
public void add_hours_to_date_in_java () {

    Calendar newYearsEve = Calendar.getInstance();
    newYearsEve.set(2012, 11, 31, 23, 0, 0);

    Calendar newYearsDay = Calendar.getInstance();
    newYearsDay.setTimeInMillis(newYearsEve.getTimeInMillis());
    newYearsDay.add(Calendar.HOUR, 1);

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

    logger.info(dateFormatter.format(newYearsEve.getTime()));
    logger.info(dateFormatter.format(newYearsDay.getTime()));

    assertTrue(newYearsDay.after(newYearsEve));
}

Output

12/31/2012 23:00:00 CST
01/01/2013 00:00:00 CST

Java 8 Date and Time API

Java 8 LocalDateTime.plusHours will return a copy of the LocalDateTime with the specified number of hours added.

@Test
public void add_hours_to_date_in_java8() {

    LocalDateTime newYearsEve = LocalDateTime.of(2012, Month.DECEMBER, 31,
            23, 0);
    LocalDateTime newYearsDay = newYearsEve.plusHours(1);

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

    logger.info(newYearsEve.format(formatter));
    logger.info(newYearsDay.format(formatter));

    assertTrue(newYearsDay.isAfter(newYearsEve));
}

Output

12/31/2012 23:00:00 0
01/01/2013 00:00:00 0

Joda Time

Joda DateTime.plusHours will return a copy the DateTime plus the specified number of hours.

@Test
public void add_hours_to_date_in_java_with_joda () {

    DateTime newYearsEve = new DateTime(2012, 12, 31, 23, 0, 0, 0);
    DateTime newYearsDay = newYearsEve.plusHours(1);

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

    logger.info(newYearsEve.toString(fmt));
    logger.info(newYearsDay.toString(fmt));

    assertTrue(newYearsDay.isAfter(newYearsEve));
}

Output

12/31/2012 23:00:00 CST
01/01/2013 00:00:00 CST

Apache Commons

Apache commons DateUtils.addHours will add a number of hours to the date returning a new object.

@Test
public void add_hours_to_date_in_java_with_apachecommons () {

    Calendar newYearsEve = Calendar.getInstance();
    newYearsEve.set(2012, 11, 31, 23, 0, 0);

    Date newYearsDay = DateUtils.addHours(newYearsEve.getTime(), 1);

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

    logger.info(dateFormatter.format(newYearsEve.getTime()));
    logger.info(dateFormatter.format(newYearsDay));

    assertTrue(newYearsDay.after(newYearsEve.getTime()));
}

Output

12/31/2012 23:00:00 CST
01/01/2013 00:00:00 CST