使用 PHP 将时间戳转换为本地时间

问题描述:

我正在尝试使用 PHP 从 mySQL 数据库中获取本地时间的时间戳,但出现错误,我使用的原始代码是这样的,显然返回了 UTC 时间:

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'); 

也是,但它也不起作用......我只做了最小的更改,因为我想将它保存在一个变量中而不是回显它.另外,在之前的答案中查看该信息,我不知道我是否可以转换任何 UTC 时间戳,或者我之前必须在我的时区中插入记录才能稍后将其转换回来.

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.

感谢您的时间.

默认情况下 DateTime::construct 使用您的本地时区.但是你的时间是 UTC,所以你需要告诉构造函数,然后然后修改时区:

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');

输出

2018-10-12 17:00:00