I’m writing an Android application and I’ve been seeing some odd behavior from Calendar so I wrote the following tests:
public void testCalendar1(){
int[] months = {
Calendar.JANUARY,
Calendar.FEBRUARY,
Calendar.MARCH,
Calendar.APRIL,
Calendar.MAY,
Calendar.JUNE,
Calendar.JULY,
Calendar.AUGUST,
Calendar.SEPTEMBER,
Calendar.OCTOBER,
Calendar.NOVEMBER,
Calendar.DECEMBER,
};
for(int i = 0; i < months.length; i++){
assertEquals(months[i], i);
}
}
public void testCalendar2(){
Calendar cal = Calendar.getInstance();
for(int i = 0; i < 12; i++){
cal.set(Calendar.MONTH, i);
assertEquals(cal.get(Calendar.MONTH), i);
}
}
I would expect both tests to pass, but the second fails with the error:
junit.framework.AssertionFailedError: expected:<2> but was:<1>
at ...
So, it seems that when the calendar month is set to 1 (February), the get method returns 2 (March). Has anyone seen behavior like this before or know what might be causing it? Or have I just done something stupid?
Note: These tests are running on an Android phone as Android junit tests.
EDIT: I’ve just realized that it’s only happening for February and today is the 30th of April. It seems I’ve answered my own question.
You have to set the
DAY_OF_MONTHto the 1st. If it is uninitialised it uses the current date which means 30.04.2012 for today. When you set the month to February it would be 30.02.2012, since this date doesn’t exist the calendar implementation switches to March.