Why does Calendar in android gives different dates in different android devices?
Calendar.getInstance
uses the system clock, so if the clocks of the different devices is set differently, you will get different times.
- Your date format uses the JVM’s default time zone (which has nothing to do with locale). Since it is never the same date in all time zones, you should get different dates (even if the system clocks are set correctly to the current time).
That said, the Calendar
and DateFormat
classes have quite heavy design problems, and I consider them long outdated. If you are doing any considerable work with dates or times in your app, you should probably use java.time instead. It is the modern Java date and time API, much better designed and so much nicer to work with.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links