Possible Duplicate:
How can I increment a date by one day in Java?
public static ArrayList<Calendar> getCalendarsForThreeYears() {
if (calendars == null) {
calendars = new ArrayList<Calendar>();
final Calendar moving = Calendar.getInstance();
final int targetYear = moving.get(Calendar.YEAR) + 1;
moving.set(moving.get(Calendar.YEAR) - 1, Calendar.JANUARY, 1);
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
while (!(moving.get(Calendar.YEAR) == targetYear
&& moving.get(Calendar.MONTH) == Calendar.DECEMBER && moving
.get(Calendar.DAY_OF_MONTH) == 31)) {
final Calendar c = (Calendar) moving.clone();
calendars.add(c);
moving.roll(Calendar.DAY_OF_MONTH, 1);
System.out.println(sdf.format(c.getTime()));
}
}
return calendars;
}
I want this to create Calendar
objects for 3 years (the one before the current, the current and the next).
However this is an infinite loop since rolling Calendar.DAY_OF_MONTH
when it's on the end of the month won't roll the Calendar.MONTH
Which is the recommended approach?