0

Why does Calendar in Android give different dates on different Android devices? I did get the default locale and still I have the same problem.

Code:

calendar = Calendar.getInstance();
currentDate = DateFormat.getDateInstance(DateFormat.DATE_FIELD,Locale.getDefault())
    .format(calendar.getTime());
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Mahmoud Ashour
  • 327
  • 4
  • 11
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `DateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 05 '18 at 08:42
  • If passing `DateFormat.DATE_FIELD` to `getDateInstance` does what you intend, it’s by coincidence. It has the value 3, and if this is what you intended, use `DateFormat.SHORT` (3 too). – Ole V.V. Dec 05 '18 at 08:44
  • Which date did you expect? How different dates do you get? The day before or the day after on some devices, or dates that are way off? For us to understand, both your situation and what’s going wrong, please state exactly which date you expect and as many examples you can of dates you actually get. Additionally it will help to know the time zone setting of the different devices. – Ole V.V. Dec 05 '18 at 08:58

1 Answers1

1

Why does Calendar in android gives different dates in different android devices?

  1. Calendar.getInstance uses the system clock, so if the clocks of the different devices is set differently, you will get different times.
  2. 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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161