Timezone conversion in php

You can use the datetime object or their function aliases for this:

Example (abridged from PHP Manual)

date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');

Edit regarding comments

but i cannt use this method because i need to show date in different time zones as the user login from different locations

That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.

in the database i need to get the dates in any single timezone, then only it can be processed properly

You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.


This worked for me and it's pretty clean too!

function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
    try {
        $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
        $dateTime->setTimezone(new DateTimeZone($userTimeZone));
        return $dateTime->format($format);
    } catch (Exception $e) {
        return '';
    }
}

function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
    try {
        $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
        $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
        return $dateTime->format($format);
    } catch (Exception $e) {
        return '';
    }
}

//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);

An even simpler method looks like this:

date_default_timezone_set('Europe/London'); // your user's timezone
$my_datetime='2013-10-23 15:47:10';
echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));

As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.

I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.