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