Subtract days from date

Opposite of adding days to a java date, this example will demonstrate how to substract a day from a date using java's Calendar.add, java 8 date time api, joda’s DateTime.minusDays and apache commons DateUtils.addDays. February 6, 2011, the date used in the examples below, was super bowl XLV between Pittsburgh Steelers and Green Bay Packers.

Straight up Java

@Test
public void subtract_days_from_date_in_java () {
    
    Calendar superBowlXLV = Calendar.getInstance();
    superBowlXLV.set(2011, 1, 6, 0, 0);
    
    Calendar pregame = Calendar.getInstance();
    pregame.setTimeInMillis(superBowlXLV.getTimeInMillis());
    pregame.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(pregame.getTime()));

    assertTrue(pregame.before(superBowlXLV));
}

Output

02/06/2011 00:00:47 CST
02/05/2011 00:00:47 CST

Java 8 Date and Time API

Java 8 LocalDate.minusDays will return a copy of the LocalDate with the specified number of days subtracted.

@Test
public void subtract_days_from_date_in_java8 () {
    
    LocalDate superBowlXLV = LocalDate.of(2011, Month.FEBRUARY, 6);
    LocalDate pregame = superBowlXLV.minusDays(1);
    
    java.time.format.DateTimeFormatter formatter = 
             java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy");

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

    assertTrue(pregame.isBefore(superBowlXLV));
}

Output

02/06/2011
02/05/2011

Joda Time

Joda DateTime.minusDays will return a copy the DateTime minus the specified number of days.

@Test
public void subtract_days_from_date_in_java_joda () {
    
    DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
    DateTime pregame = superBowlXLV.minusDays(1);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
    
    logger.info(superBowlXLV.toString(fmt));
    logger.info(pregame.toString(fmt));

    assertTrue(pregame.isBefore(superBowlXLV));
}

Output

02/06/2011 00:00:00 CST
02/05/2011 00:00:00 CST

Apache Commons

Apache commons DateUtils.addDays will adds a number of days, in this case a negative number of days, to the date returning a new object.

@Test
public void subtract_days_from_date_in_java_apachecommons () {
    
    Calendar superBowlXLV = Calendar.getInstance();
    superBowlXLV.set(2011, 1, 6, 0, 0);
    
    Date pregame = 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(pregame));

    assertTrue(pregame.before(superBowlXLV.getTime()));
}

Output

02/06/2011 00:00:05 CST
02/05/2011 00:00:05 CST