converting timestamp to local time with PHP

2019-03-03 14:28发布

问题:

I'm trying to get a timestamp in local time with PHP from a mySQL database and I'm gettin errors, the original code that I was using was this, that obviously returned the UTC time:

$timestamp = strtotime($row['created']);
$dt = date('d/m/Y H:i', $timestamp);

Now searching in previous answers I've found this code:

$date = /* SELECT date FROM database */;
$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
echo $l10nDate->format('Y-m-d H:i:s');

But I couldn't make it work... I tried adding date_default_timezone_set('America/Vancouver'); too, but it dind't work neither... and I only did minimum changes because I want to save it in a variable not echo it. Also, looking that information in that previous answer, I don't know neither if I can convert any UTC timestamp, or I have to insert the record in my timezone previously to can convert it back later.

Thanks for your time.

回答1:

By default DateTime::construct uses your local timezone. However your time is in UTC, so you need to tell the constructor that, and then modify the timezone:

$date = '2018-10-13 00:00:00';
$l10nDate = new DateTime($date, new DateTimeZone('UTC'));
$l10nDate->setTimeZone(new DateTimeZone('America/Vancouver'));
echo $l10nDate->format('Y-m-d H:i:s');

Output

2018-10-12 17:00:00