Opposite of subtracting minutes from a java date, this example will show how to add minutes to a date using Calendar.add, java 8 date time api, joda’s DateTime.plusMinutes and apache commons DateUtils.addMinutes. In the examples below, we will set a date that represents new years eve, December 31st, then add minutes to return a date representing new years day or January 1st.
Straight up Java
@Test
public void add_minutes_to_date_in_java () {
Calendar newYearsEve = Calendar.getInstance();
newYearsEve.set(2012, 11, 31, 23, 59, 0);
Calendar newYearsDay = Calendar.getInstance();
newYearsDay.setTimeInMillis(newYearsEve.getTimeInMillis());
newYearsDay.add(Calendar.MINUTE, 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:59:00 CST
01/01/2013 00:00:00 CST
Java 8 Date and Time API
Java 8 LocalDateTime.plusMinutes will return a copy of the LocalDateTime with the specified number of minutes added.
@Test
public void add_minutes_to_date_in_java8() {
LocalDateTime newYearsEve = LocalDateTime.of(2012, Month.DECEMBER, 31,
23, 59);
LocalDateTime newYearsDay = newYearsEve.plusMinutes(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:59:00 0
01/01/2013 00:00:00 0
Joda Time
Joda DateTime.plusMinutes will return a copy the DateTime plus the specified number of minutes.
@Test
public void add_minutes_to_date_in_java_with_joda () {
DateTime newYearsEve = new DateTime(2012, 12, 31, 23, 59, 0, 0);
DateTime newYearsDay = newYearsEve.plusMinutes(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:59:00 CST
01/01/2013 00:00:00 CST
Apache Commons
Apache commons DateUtils.addMinutes will adds a number of minutes to the date returning a new object.
@Test
public void add_minutes_to_date_in_java_with_apachecommons () {
Calendar newYearsEve = Calendar.getInstance();
newYearsEve.set(2012, 11, 31, 23, 59, 0);
Date newYearsDay = DateUtils.addMinutes(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:59:00 CST
01/01/2013 00:00:00 CST