Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get TimeZone offset value from TimeZone without TimeZone name

Tags:

java

timezone

I need to save the phone's timezone in the format [+/-]hh:mm

I am using TimeZone class to deal with this, but the only format I can get is the following:

PST -05:00 GMT +02:00 

I would rather not substring the result, is there any key or option flag I can set to only get the value and not the name of that timezone (GMT/CET/PST...)?

like image 540
Mr Bean Avatar asked Jul 09 '12 16:07

Mr Bean


People also ask

How do I find the offset of time zones?

You can get the offset of a timezone using ZonedDateTime#getOffset . Note that the offset of a timezone that observes DST changes as per the changes in DST. For other places (e.g. India), it remains fixed. Therefore, it is recommended to mention the moment when the offset of a timezone is shown.

How do I get UTC offset from timezone?

Timezone offset is the time difference in hours or minutes between the Coordinated Universal Time (UTC) and a given time zone. The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time.

How can I get the timezone name in JavaScript?

In javascript , the Date. getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

What is timezone getDefault ()?

The getDefault() method is used to get the default TimeZone for this host. The source of the default TimeZone may vary with implementation.


1 Answers

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.

like image 171
Tomasz Nurkiewicz Avatar answered Oct 02 '22 08:10

Tomasz Nurkiewicz