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!
Related Link: http://php.net/manual/en/class.datetime.php