How to convert time/timezones with PHP

Written by: Chris in How-To, Web Technology

Note: This method requires PHP 5.2 (or the experimental feature in 5.1).


Let’s say you’ve got an application running in the timezone America/Toronto. Let’s say you want to know what a certain time will be in another time zone, Europe/London. One way to do this would be to swap the active time zone PHP is using and use strtotime(), but this could lead to odd behaviours depending on how PHP (and its host server) is running.

There’s a much easier and simpler way to do this in PHP 5.2: the DateTime class.

Here’s a quick run-down: The constructor accepts two parameters, a time string (interpreted like strtotime() would) and a DateTimeZone object which in turn accepts a parameter of a timezone string. You can then query the object for the date in a particular format. For example:

$dt = new DateTime('yesterday', new DateTimeZone('Europe/London'));
echo $dt->format('Y-m-d H:i:s');

Assuming the current date is the 14th of June, this would give me a response of 2011-06-13 00:00:00. To preserve the time I could instead use:

$dt = new DateTime('-1 day', new DateTimeZone('Europe/London'));
echo $dt->format('Y-m-d H:i:s');

At 12:28 on the same day, this would net me a response of 2011-06-13 17:28:37, correctly shifting the time ahead five hours.

Be careful in the usage of this object: A Unix timestamp is always UTC. Furthermore, using an absolute time in the constructor can lead to unexpected results:

$dt = new DateTime('20:00', new DateTimeZone('Europe/London'));
echo $dt->format('Y-m-d H:i:s');

One may expect the time to be shifted ahead; Instead, I get the response 2011-06-14 20:00:00. Why? Because I specified that exact time, so it assumed I wanted that time in that time zone, and not the current time shifted to that time zone. The correct way to do this would be to set the time, then change the time zone, like so:

$dt = new DateTime('20:00');
$dt->setTimezone(new DateTimeZone('Europe/London'));
echo $dt->format('Y-m-d H:i:s');

And voilà, the response is 2011-06-15 01:00:00.

If PHP complains about not trusting the server’s time zone, you can also set your time zone with the second parameter as I did in the first example, and then change it like the example right above:

$dt = new DateTime('20:00', new DateTimeZone('America/Toronto'));
$dt->setTimezone(new DateTimeZone('Europe/London'));
echo $dt->format('Y-m-d H:i:s');

Once again this will correctly return 2011-06-15 01:00:00. Remember, any string valid for strtotime() can be passed as the first parameter in the constructor.

One Response to “How to convert time/timezones with PHP”