dealing with timezones in php

so i was working on some code in which i needed to know whether or not it was dst for a given country and/or timezone or not. luckily, with php5.2, some sparsely documented (yet very useful) classes were introduced - a more thorough documentation can be found here.

so let’s say i want to know whether or not egypt is in dst right now or not… so first i need to know what zoneinfo file egypt uses (for egypt, it’s simple, but this trick is useful for more obscure places, like “isle of man,” for example):

cd /usr/share/zoneinfo
grep -i egypt iso*.tab        # get the iso country code for egypt

# the above command returns 'EG' - so...
grep EG
# returns 'Africa/Cairo'

in many cases, there are many timezones that exist for a given country. in many cases, it’s obvious which file you need, but in some cases, it’s not very obvious. in those cases, i found it helpful to open the binary files and look at the very last line, in which some hint about the offset of the timezone is given.

anyway… once you have the zoneinfo file that you would use, it’s very easy to find whether or not you are in dst (well, assuming that you know what the standard, non-dst offset from utc is). for example:

$tz = new DateTimeZone('America/New_York');
$date = new DateTime();
echo $date->;format(DATE_RFC3339) . "\n";
echo $date->getOffset()/3600 . "\n";

running this returns the time in new york, and the offset (-4). since the standard est offset is -5 hours, -4 means we’re +1 which means we are currently on dst.

so if you don’t know the standard offset, another trick that you could do is pass some parameters to the new DateTime() constructor - so for example…

$tz = new DateTimeZone('America/New_York');
$date = new DateTime('2008-12-31');
echo $date->getOffset()/3600 . "\n";

this returns -5, which is out of dst. anyhow, you could use the above if you don’t know the default offset for a timezone for dst by passing in 2 dates - something towards the middle of the year (july-ish) and something towards the end of the year (december-ish). if the offsets are different, the place probably has dst.

also, do note that some places have things a little differently - so dst in windhoek, namibia, for example, ends in april and starts in september.

comments powered by Disqus