PHP convert UTC time to local time

Use function date_default_timezone_set before there you want to local time after that again setup UTC Europe/Lisbon timezone List of Supported Timezones

  <?php

$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc);
echo "<br/>Defualt UTC/server time".$dateInLocal = date("Y-m-d H:i:s", $time);

//your local time zone put here
date_default_timezone_set('Asia/Kolkata');

echo "<br/>Local time". $dateInLocal = date("Y-m-d H:i:s", $time);
?>

Simply use a DateTimeZone, eg

$dt = new DateTime($utc);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after

$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');

Demo ~ http://ideone.com/fkM4ct


If this is not done via a user profile setting, it is probably easier and simpler to use a javascript time library eg. moment.js (http://momentjs.com/) to solve this problem (send all date/times in UTC and then convert them on the client end).

Javascript eg. (I am sure this can be achieved without creating two moment objects (fix that at your leisure).

function utcToLocalTime(utcTimeString){
    var theTime  = moment.utc(utcTimeString).toDate(); // moment date object in local time
    var localTime = moment(theTime).format('YYYY-MM-DD HH:mm'); //format the moment time object to string

    return localTime;
}

php example for server side resolution (only use one of these solutions, both together will produce an incorrect time on the client end)

/**
 * @param $dateTimeUTC
 * @param string $timeZone
 * @param string $dateFormat
 * @return string
 *
 * epoch to datetime (utc/gmt)::
 * gmdate('Y-m-d H:i:s', $epoch);
 */
function dateToTimezone($timeZone = 'UTC', $dateTimeUTC = null, $dateFormat = 'Y-m-d H:i:s'){

    $dateTimeUTC = $dateTimeUTC ? $dateTimeUTC : date("Y-m-d H:i:s");

    $date = new DateTime($dateTimeUTC, new DateTimeZone('UTC'));
    $date->setTimeZone(new DateTimeZone($timeZone));

    return $date->format($dateFormat);
}

The reason your code isn't working is most likely because your server is in UTC time. So the local time of the server is UTC.

Solution #1

One potential solution is to do the following server side and pass the epoch integer to the browser:

$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc); //returns an integer epoch time: 1401339270

Then use JavaScript to convert the epoch integer to the user's local time (the browser knows the user's timezone).

Solution #2

You can get the browser to send you the user's timezone. Then you can use this information to calculate the date string server side instead of browser side. See more here: https://stackoverflow.com/a/5607444/276949

This will give you the user's offset (-7 hours). You can use this information to set the timezone by looking here: Convert UTC offset to timezone or date