PHP 将 UTC 时间转换为本地时间

PHP converting UTC to Local Time

在我的 postgresql 中,我有一个名为 "created" 的以下列,其类型为 timestamp with timezone

所以我按照我认为是 UTC 的格式插入了记录。

2015-10-02 09:09:35+08

我正在使用 php Carbon 库,所以我做了以下操作:

$date = Carbon\Carbon::parse('2015-10-02 09:09:35+08');
echo  $date->->toDatetimeString(); 
//gives result as 2015-10-02 09:09:35

如何使用库来回显正确的时区,包括在上述日期时间格式中添加 +8?我使用的 timzezone 是 "Asia/Singapore".

时间应打印为本地时间 2015-10-02:17:09:35:

试试这个:

$timestamp = '2015-10-02 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Asia/Singapore');

尝试使用标准 PHP:

$raw = '2015-10-02 09:09:35+08';
$date = substr($raw,0,19);
$tzOffset = (strlen($raw) > 19) ? substr($raw,-3) : 0;
$timestamp = strtotime($date) + (60 * 60 * $tzOffset);
$localTime = date('Y-m-d H:i:s',$timestamp);
echo 'local time:['.$localTime.']';

结果是:

local time:[2015-10-02 17:09:35]

这也适用于没有时区偏移或负时差的情况。

您可以使用本机 php 而无需使用 Carbon:

$time = '2015-10-02 16:34:00+08';
$date = DateTime::createFromFormat('Y-m-d H:i:s+O', $time);
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Asia/Singapore'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Etc/UTC'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;