PHP将UTC转换为本地时间

时间:2015-10-02 09:42:42

标签: php yii php-carbon

在我的postgresql中,我有以下列名为"创建"类型带时区的时间戳

所以我按照格式插入记录,我相信是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是"亚洲/新加坡"

时间应打印到当地时间,即2015-10-02:17:09:35:

3 个答案:

答案 0 :(得分:1)

使用标准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]

这也可以在没有时区偏移或负时偏移的情况下工作。

答案 1 :(得分:1)

你可以使用本机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;

答案 2 :(得分:0)

试试这个:

class Item {
    String description;

    public Item(String description) {
        this.description = description;
    }

    abstract double getPrice();
}