Search code examples
javadatecalendardayofweek

Adding one week via java.util.Calendar.add() fails


I'm trying to iterate in my Java program over all weeks between two dates (the end date being today). First, I get the starting date:

Calendar start = Calendar.getInstance();
start = data.getFirstDate(users, threads);

So far, so good. The start date is correct and I can work with it. Now I iterate:

Calendar current = start;
while(current.before(Calendar.getInstance()) {
    // Do something
    current.add(Calendar.DATE, 7);
}

Well, this kind of works. I start at 2002/8/23, then comes 2002/8/30, then 2002/9/7... UNTIL 2002/11/30. The date after that is 2003/0/6, which is neither correct nor even a valid date!

What am I doing wrong? I tried current.add(Calendar.DATE, 7), current.add(Calendar.WEEK_OF_YEAR, 1), current.add(Calendar.DAY_OF_YEAR, 7) and two other ways. Using current.roll(Calendar.DATE, 7) does not work because I stay in the same month. Using GregorianCalendar has no effect as well.

Any suggestions would be greatly appreciated!

Thanks Julian


Solution

  • The month field in the Calendar API is 0-based not 1-based. So 0 stands for January. Don't ask me why.