1

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?

Community
  • 1
  • 1
Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90

3 Answers3

2

You should use moving.add(Calendar.DAY_OF_MONTH, 1);, since roll will add the days but will not add another month when you reach the last day in month before adding a new day. In other words, if your month is say "June" you will get 1st, 2nd, 3rd ... 30th of june, then you would expect 1st july, but you will start over at 1st june.

Carnal
  • 21,744
  • 6
  • 60
  • 75
2
moving.add(Calendar.DATE, 1);

will do what you want.

See Calendar#add(int, int):

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.

And Calendar.DATE:

Field number for get and set indicating the day of the month.

Baz
  • 36,440
  • 11
  • 68
  • 94
1

Its a simple use the add() method of the Calendar. If you want to add the year then use like calendar.add(Calendar.YEAR, 1); or to reduce the year calendar.add(Calendar.YEAR, -1);. After setting proper datetime you can convert the date into your format using the SimpleDateFormat.

Dharmendra
  • 33,296
  • 22
  • 86
  • 129