PHP: How to Convert a Date/Time from UTC to another Time Zone Programming 27 MAR 2015

Having previously shown you a useful way of quickly converting a timestamp into a formatted date string, here’s a quick way of actually getting a date/time in a time zone that you actually want – and again we turn to the powerfull PHP DateTime class to do this for us.

//here we'll use a UTC (time zone independent) time for our example
//(remember, time() always returns a UTC timestamp)
$dateTimeEnd = new DateTime('@' . time());
echo $dateTimeEnd->format('Y-m-d H:i:s');            
//now let's change to GMT+2 (SAST - South African Standard Time)
$dateTimeEnd->setTimezone(new DateTimeZone('Africa/Johannesburg'));
echo $dateTimeEnd->format('Y-m-d H:i:s');

As you can see, the setTimezone function of the DateTime class does all the heavy lifting for us, making it a snap to convert timestamps between different time zones.

Just a note, if you want to get the current time zone that your script is executing under, you can make use of date_default_timezone_get:

if (date_default_timezone_get()) {
    echo 'current time zone: ' . date_default_timezone_get() . '<br />';
}

A handy tip to remember then in other words!

world map showing time zones

Related Link: http://php.net/manual/en/class.datetime.php

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.