Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timezone in PHP

Tags:

date

timezone

php

PHP seems to use a rather annoying method for setting the evnironment timezone, using region names rather than the GMT offset. This makes having a timezone dropdown a huge pain, because it either has to be huge to accommodate all possible PHP timezone values, or I have to find a way to convert a GMT offset to a valid value to pass to PHP.

So, given a GMT offset, how might I set the timezone in PHP? For example, how might I convert the GMT offset value of "-8.0" to a value that I could pass to date_timezone_set()?

like image 312
Wilco Avatar asked Nov 28 '22 12:11

Wilco


2 Answers

Using a region name is the right way to describe a time zone. Using a GMT offset on its own is hugely ambiguous.

This is reflected in your question - how should you convert a GMT offset of -8 into a time zone? Well, that depends on what "GMT -8" really means. Does it mean "UTC -8 at every point in time" or does it mean "UTC -8 during winter time, and UTC -7 in summer time"? If it's the latter, when does winter start and end?

I would hope that PHP accepted a well-known set of values for the "fixed" (no DST) time zones, e.g. "Etc/GMT+3" etc. But unless you really, really mean a fixed time zone, you're better off finding out which region you're actually talking about, because otherwise your calculations are almost guaranteed to be wrong at some point.

I've been wrestling with time zones for most of the last year. They're a pain - particularly when some zones change their rules for DST (like the US did a few years ago) or when some zones opt in and out of DST seemingly at will. Trying to reflect all of this in a single number is folly. If you're only interested in a single instant in time, it might be okay - but at that point you might as well just store the UTC value in the first place. Otherwise, a name is the best approach. (It's not necessarily plain sailing at that point, mind you. Even the names change over time...)

like image 122
Jon Skeet Avatar answered Dec 10 '22 18:12

Jon Skeet


If you are using PHP >= 5.2, you can use the built-in DateTimeZone class method, listAbbreviations.

var_dump( DateTimeZone::listAbbreviations() );
like image 25
Jeff Ober Avatar answered Dec 10 '22 19:12

Jeff Ober