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

丶灬走出姿态 提交于 2019-12-23 15:08:05

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/14118777/converting-date-to-milliseconds-is-giving-inconsistent-results-in-android-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!