0

On Android how can I obtain timezone offset from UTC based on my current location? I dont want to use any 3rd party web service or include tz_world database to my app.

If I move acrros timezone border, my phone changes time automatically. Is it possible to obtain the offset absed on this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Martin Mickey
  • 333
  • 4
  • 13

2 Answers2

3

Since time zones tend to have summer time (DST) and other anomalies, there is a difference between obtaining the time zone and obtaining the offset from UTC. The latter requires not only a location, but also a time of year.

The modern way to obtain the time zone:

    ZoneId timeZone = ZoneId.systemDefault();

On my Mac I got Europe/Copenhagen. Beware, however, that what this gives you, is the time zone setting of your JVM. This won’t change when the device’s setting changes. To make matters worse, the JVM setting may be changed from other parts of your program or from other programs running in the same JVM. Only when the JVM is restarted, it will pick up the device setting.

To get the current offset from UTC:

    ZoneOffset offsetFromUtc = timeZone.getRules().getOffset(Instant.now());

In my case I got +01:00. Pass a different Instant if you want the offset from another time of year.

I am using java.time, the modern Java date and time API. I am told that it’s built in on newer Android devices. To use it on an older device, get ThreeTenABP, add it to your project and make sure you import the date and time classes from the org.threeten.bp package. See the links below.

Links

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

Try this

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone: "+tz.getDisplayName());