Get TimeZone offset value from TimeZone without TimeZone name
With Java 8, you can achieve this with the following code:
TimeZone tz = TimeZone.getDefault();
String offsetId = tz.toZoneId().getRules().getStandardOffset(Instant.now()).getId();
and the offsetId
will be something like +01:00
.
Please notice the function getStandardOffset()
needs an Instant
as parameter. It is the specific time point, at which you want to check the offset of given timezone, as timezone's offset may vary during time. For the reason of some areas have Daylight Saving Time.
I think it is the reason why @Tomasz Nurkiewicz recommands not to store offset in signed hour format directly, but to check the offset each time you need it.
@MrBean - I was in a similar situation where I had to call a 3rd-party web service and pass in the Android device's current timezone offset in the format +/-hh:mm. Here is my solution:
public static String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
I need to save the phone's timezone in the format [+/-]hh:mm
No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to dst) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.
So instead of storing + 02:00
(or should it be + 01:00
?) I store "Europe/Oslo"
in my database. Now I can restore full configuration using:
TimeZone tz = TimeZone.getTimeZone("Europe/Oslo")
Want to know what is my time zone offset today?
tz.getOffset(new Date().getTime()) / 1000 / 60 //yields +120 minutes
However the same in December:
Calendar christmas = new GregorianCalendar(2012, DECEMBER, 25);
tz.getOffset(christmas.getTimeInMillis()) / 1000 / 60 //yields +60 minutes
Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use TimeZone.getAvailableIDs()
to enumerate all supported timezone IDs.
With Java 8 now, you can use:
Integer offset = ZonedDateTime.now().getOffset().getTotalSeconds();
to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case.
Example: https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html