简体   繁体   中英

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.

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).

Try this:

      Calendar cal4 = Calendar.getInstance();
      cal4.setTime((Date)d.clone());    // <-- Update 
      Log.d(TAG,"cal4 time: " + cal4.getTime().toString());

      cal4.set(Calendar.HOUR_OF_DAY, 0);

      Log.d(TAG,"cal4 time: " + cal4.getTime().toString());

Output:

cal4 time: Fri Mar 27 19:02:55 EDT 2015
cal4 time: Fri Mar 27 00:02:55 EDT 2015

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM