Opposite of subtracting weeks from a java date, this example will show how to add weeks to a date using Calendar.add, java 8 date time api, joda DateTime.plusWeeks and apache common DateUtils.addWeeks. In the examples below, we will set a date that represents christmas, December 25th, then add a week to return a date representing new years day or January 1st.
Straight up Java
@Test
public void add_weeks_to_date_in_java () {
Calendar xmas = Calendar.getInstance();
xmas.set(2012, 11, 25, 0, 0, 0);
Calendar newYearsDay = Calendar.getInstance();
newYearsDay.setTimeInMillis(xmas.getTimeInMillis());
newYearsDay.add(Calendar.WEEK_OF_YEAR, 1);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
logger.info(dateFormatter.format(xmas.getTime()));
logger.info(dateFormatter.format(newYearsDay.getTime()));
assertTrue(newYearsDay.after(xmas));
}
Output
12/25/2012 00:00:00 CST
01/01/2013 00:00:00 CST
Java 8 Date and Time API
Java 8 LocalDateTime.plusWeeks will return a copy of the LocalDateTime with the specified number of weeks added.
@Test
public void add_weeks_to_date_in_java8() {
LocalDateTime xmas = LocalDateTime.of(2012, Month.DECEMBER, 25, 0, 0);
LocalDateTime newYearsDay = xmas.plusWeeks(1);
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(xmas.format(formatter));
logger.info(newYearsDay.format(formatter));
assertTrue(newYearsDay.isAfter(xmas));
}
Output
12/25/2012 00:00:00 0
01/01/2013 00:00:00 0
Joda Time
Joda DateTime.plusWeeks will return a copy the DateTime plus the specified number of weeks.
@Test
public void add_weeks_to_date_in_java_with_joda () {
DateTime xmas = new DateTime(2012, 12, 25, 0, 0, 0, 0);
DateTime newYearsDay = xmas.plusWeeks(1);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
logger.info(xmas.toString(fmt));
logger.info(newYearsDay.toString(fmt));
assertTrue(newYearsDay.isAfter(xmas));
}
Output
12/25/2012 00:00:00 CST
01/01/2013 00:00:00 CST
Apache Commons
Apache commons DateUtils.addWeeks will adds a number of weeks to the date returning a new object.
@Test
public void add_weeks_to_date_in_java_with_apachecommons () {
Calendar xmas = Calendar.getInstance();
xmas.set(2012, 11, 25, 0, 0, 0);
Date newYearsDay = DateUtils.addWeeks(xmas.getTime(), 1);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
logger.info(dateFormatter.format(xmas.getTime()));
logger.info(dateFormatter.format(newYearsDay));
assertTrue(newYearsDay.after(xmas.getTime()));
}
Output
12/25/2012 00:00:00 CST
01/01/2013 00:00:00 CST