Add a number of weeks to a date returning a new object in Java
Description
The following code shows how to add a number of weeks to a date returning a new object.
Example
/* w w w. ja v a2 s.c om*/
import java.util.Calendar;
import java.util.Date;
public class Main {
public static Date addWeeks(Date date, int amount) {
return add(date, Calendar.WEEK_OF_YEAR, amount);
}
private static Date add(Date date, int calendarField, int amount) {
if (date == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(calendarField, amount);
return c.getTime();
}
public static void main(String[] argv) {
Date date = new Date();
System.out.println(addWeeks(date, 100));
}
}
The code above generates the following result.