Search code examples
javaandroidcalendargregorian-calendar

Clearing Calendar.HOUR adds hundreds of days


I'm using the lines of code:

1  GregorianCalendar cal = (GregorianCalendar) date.clone();
2  cal.clear(Calendar.HOUR);

When using this code in a unit test - it runs just fine. However when running it on my Android device, it seems to break. Here is what my debugger says:

After line 1: cal.getTimeInMillis() = 1426022494179
After line 2: cal.getTimeInMillis() = 1450905694179

I've also tried cal.set(Calendar.HOUR, 0) and it does the same thing.

EDIT: After some testing, it appears that setting or clearing anything on the cal object immediately puts me to December 24 of the year you are currently in. However, once the initial switch to Dec 24 happens, the Calendar then acts normally.


Solution

  • I found the issue. It appears Android SDK 21 has a bug - when using getActualMaximum(Calendar.WEEK_OF_YEAR) on the GregorianCalendar, it puts the object into a state such that if you use a set() call before a get() call, it will put your date to December 31 or 23 (depending on the year).