Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date to milliseconds is giving inconsistent results in Android (java)

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?

like image 236
Shdus Avatar asked Jan 15 '23 15:01

Shdus


1 Answers

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();
like image 133
jlordo Avatar answered Jan 21 '23 14:01

jlordo