I'm trying to work with a calendar in android, and when I try to convert a date into milliseconds, I get different results on different runs.
When I print out the values of milliseconds1 and milliseconds2, I get different results 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 Android's implementation) or something like that?
The answer to your question is: No, this is not a bug in Java or Android. It is well documented behavior. A Calendar
instance has more fields than YEAR, MONTH and DATE. You generate new calendar instances and only change those fields, leaving all other fields the way the were created. If you run your program twice in a row, the seconds and milliseconds will have changed in the mean time.
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, call clear() first.
In order to print the same value every time, you need to do this:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With