Mahmoud Ashour
Mahmoud Ashour

Reputation: 327

Calendar date is different

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

Upvotes: 0

Views: 121

Answers (1)

Anonymous
Anonymous

Reputation: 86148

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

Upvotes: 1

Related Questions