简体   繁体   中英

android surprising difference between Date and GregorianCalendar - bug?

I have the following code:

public static final long ONE_DAY_IN_MILLISECONDS = 24*60*60*1000;
(...)
Date newNextTestDate = new Date ( (new Date().getTime()) + newInterval*ONE_DAY_IN_MILLISECONDS);
System.out.println("data: " +newNextTestDate.getTime());

GregorianCalendar tmp2Date = new GregorianCalendar ();
tmp2Date.add(GregorianCalendar.DAY_OF_MONTH, newInterval);
System.out.println(" data2: " +tmp2Date.getTimeInMillis());

//where newInterval is number of days (int)

In Android 4.0.4 and 4.2.2 in 2/3 of cases the displayed values are the same (sometimes minor difference). However in 1/3 of cases there is the difference of.... 3600000 (or something similar like 3600001) which is the equivalent of one hour. Moreover if I have this in a loop, it seems to be fully random, on the same device, without touching any system settings, sometimes that difference exist and sometimes not. Is there any bug in Android implementation of Date?

I don't know what is the reason of problems, but I've found the workaround.

When instead of using new Date() I use (new GregorianCalendar()).getTime this strange "effect" doesn't appear.

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