0

I am trying to find the timezone of the android phone. Because I want to get the date object but I want in GMT+4 format. Every other answer I saw converts the time coming from an API request(whose timezone is known). How can I accomplish this?

Other approach may be converting the GMT+4 time that comes to me from server to the local time of my device.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Prethia
  • 1,183
  • 3
  • 11
  • 26
  • Using java.time, the modern Java date and time API: `OffsetDateTime.now(ZoneOffset.ofHours(4))`. – Ole V.V. Sep 13 '18 at 14:58
  • If you mean the `java.util.Date` object, that cannot have `GMT+4` offset (which isn’t a format, BTW). A `Date` neither has time zone, offset nor format. Apparently related: [Java: Calculate month end date based on timezone](https://stackoverflow.com/questions/51644208/java-calculate-month-end-date-based-on-timezone). – Ole V.V. Sep 13 '18 at 15:02

1 Answers1

1

Best to use a real time zone rather than just an offset of +04. For example:

    OffsetDateTime currentDateTimeInGeorgia = OffsetDateTime.now(ZoneId.of("Asia/Tbilisi"));
    System.out.println(currentDateTimeInGeorgia);

This snippet just output:

2018-09-13T19:18:35.642592+04:00

Please substitute your own time zone. If you do insist on GMT+4, use ZoneOffset.ofHours(4).

The old Date class cannot hold an offset or time zone, but the modern OffsetDateTime does, as the name says. The Date class is also poorly designed, so do consider using java.time, the modern Java date and time API.

As you see, the above doesn’t use the device time zone. If you need this anyway:

    ZoneId deviceTimeZone = ZoneId.systemDefault();
    System.out.println(deviceTimeZone);

Example output:

Asia/Dubai

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, I’m told) 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