Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 220
Julian Avatar asked Dec 13 '22 17:12

Julian


1 Answers

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

like image 194
hleinone Avatar answered Jan 03 '23 13:01

hleinone