Time Zone Conversion Using PHP DateTime Class
Following on from my post last month about problems with PEAR daylight saving, here’s a quick example of using the PHP DateTime Class which was introduced recently (PHP 5.2).
Convert from UTC to Europe/London local time:
$time_object = new DateTime('2011-04-19 17:45', new DateTimeZone('UTC'));
$time_object->setTimezone(new DateTimeZone('Europe/London'));
$LondonDateTime = $time_object->format('Y-m-d H:i:s');
This will work with daylight saving too.
Here’s that example wrapped up in a handy time zone conversion function:
function convert_time_zone($date_time, $from_tz, $to_tz)
{
$time_object = new DateTime($date_time, new DateTimeZone($from_tz));
$time_object->setTimezone(new DateTimeZone($to_tz));
return $time_object->format('Y-m-d H:i:s');
}
Just wanted to say thanks for posting this. It helped me out.
Thanks! A real life saver!
really helpful code. thanks.
Works. Thanks!
Many thanks for this function :)
Hey, thanks A LOT!
[…] http://richardwillia.ms/blog/2011/04/time-zone-conversion-using-datetime-class/ […]
The above post TIME ZONE CONVERSION USING PHP DATETIME CLASS automatically considers day light savings and convert the time according to time zone give. Can you please write a function that converts time without considering day light saving …
Many Many Thanks for your code.Really helpful code.
Thanks very much! this has helped me a lot!
Thank you for the cut-paste solution, works excellent. J