Converting a date to milliseconds gives inconsistent results in Android (java)

I try to work with the calendar in android, and when I try to convert the date to milliseconds, I get different results with different runs.

When I print the values ​​of milliseconds1 and milliseconds2, I get different results at different times!

My code is as follows:

Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar1.set(1997, 9, 3); calendar2.set(1997, 9, 01); long milliseconds1 = calendar1.getTimeInMillis(); long milliseconds2 = calendar2.getTimeInMillis(); 

Is this a bug in Java (or an implementation of Android) or something like that?

+4
source share
1 answer

The answer to your question: No , this is not a bug in Java or Android. This is a well-documented behavior. A Calendar instance has more fields than YEAR, MONTH, and DATE. You create new instances of the calendar and change only these fields, leaving all other fields as they were created. If you run your program twice in a row, seconds and milliseconds will change on average.

From JavaDoc :

Sets the values ​​for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values ​​of other calendar fields are retained. If this is not desired, first call clear () .

To print the same value each time, you need to do the following:

  Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar1.clear(); calendar1.set(1997, 9, 3); calendar2.clear(); calendar2.set(1997, 9, 1); long milliseconds1 = calendar1.getTimeInMillis(); long milliseconds2 = calendar2.getTimeInMillis(); 
+8
source

All Articles