Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Timezone Offset into Name

I am using Javascript to store a user's current GMT offset timezone and I would like to convert it to the PHP Timezone Name.

If I have an offset of say "300" or "-200" how can I convert it into the php timezone Name?

Thanks!

like image 640
ackerchez Avatar asked Mar 06 '12 20:03

ackerchez


People also ask

How do you get a time zone name?

DateTimeFormat() method to get the time zone name, e.g. Intl. DateTimeFormat(). resolvedOptions(). timeZone The resolvedOptions method returns a new object, on which you can access the timeZone property to get the name of the time zone.

How do I change timezone to offset?

To convert UTC to a different time zone, we can use the NOW() function to subtract/add the offset to UTC and divide by 24. Returns the date and time in offset time zone.

How do I get current time zone in JavaScript?

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. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.


1 Answers

Unfortunately, I came across your question just now, so the answer may seem late a bit, but nevertheless I'm posting it.

You definitely can convert time offset into timezone name. Basically this is performed by the following line of code:

$zoneName = timezone_name_from_abbr('', $offset*3600);

where $offset is a time offset in hours. This simplified method may fail under certain conditions due to some known bugs/features in PHP, so there is an extended wrapper with a workaround, which can be found on php.net site. Among other things, the wrapper supports daylight savings flag as well.

Indeed, as @zerkms noted in his answer, there is no one-to-one relation between time offset and timezone name, because several timezones do usually share the same offset. This function returns the first found time zone corresponding to given offset. Which one exactly goes the first, is not predefined.

But anyway, this function is very handy for setting preferred timezone for a user session via date_default_timezone_set, which accepts timezone identifier only, but user may be presented with time offsets in web UI. We don't care which identifier is used (behind the scenes) as long as we know that time offset is correct.

like image 52
Stan Avatar answered Sep 21 '22 02:09

Stan