Subtract weeks from date

Opposite of adding weeks to a java date, this example shows how to subtract weeks from a date using java's Calendar.add, java 8 date time api, joda’s DateTime.minusWeeks and apache commons DateUtils.addWeeks. In each of the examples below, we will set a date that represents new years day or January 1st. Then we will subtract one week returning a date representing christmas or December 25th.

Straight up Java

@Test
public void subtract_weeks_from_date_in_java () {
    
    Calendar newYearsDay = Calendar.getInstance();
    newYearsDay.set(2013, 0, 1, 0, 0, 0);
    
    Calendar xmas = Calendar.getInstance();
    xmas.setTimeInMillis(newYearsDay.getTimeInMillis());
    xmas.add(Calendar.WEEK_OF_YEAR, -1);        
    
    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

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

    assertTrue(xmas.before(newYearsDay));
}

Output

01/01/2013 00:00:00 CST
12/25/2012 00:00:00 CST

Java 8 Date and Time API

Java 8 LocalDateTime.minusWeeks will return a copy of the LocalDateTime with the specified number of weeks subtracted.

@Test
public void subtract_weeks_from_date_in_java8() {

    LocalDateTime newYearsDay = LocalDateTime.of(2013, Month.JANUARY, 1, 0,
            0);
    LocalDateTime xmas = newYearsDay.minusWeeks(1);

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

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

    assertTrue(xmas.isBefore(newYearsDay));
}

Output

01/01/2013 00:00:00 0
12/25/2012 00:00:00 0

Joda Time

Joda DateTime.minusWeeks will return a copy the DateTime minus the specified number of weeks.

@Test
public void subtract_weeks_from_date_in_java_with_joda () {
    
    DateTime newYearsDay = new DateTime(2013, 1, 1, 0, 0, 0, 0);
    DateTime xmas = newYearsDay.minusWeeks(1);

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

    assertTrue(xmas.isBefore(newYearsDay));
}

Output

01/01/2013 00:00:00 CST
12/25/2012 00:00:00 CST

Apache Commons

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

@Test
public void subtract_weeks_from_date_in_java_apachecommons () {
    
    Calendar newYearsDay = Calendar.getInstance();
    newYearsDay.set(2013, 0, 1, 0, 0, 0);
    
    Date xmas = DateUtils.addWeeks(newYearsDay.getTime(), -1);
    
    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

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

    assertTrue(xmas.before(newYearsDay.getTime()));
}

Output

01/01/2013 00:00:00 CST
12/25/2012 00:00:00 CST