首页 > 解决方案 > 使用 PHP 将时区字符串转换为 UTC 偏移量

问题描述

我有一个 Wordpress 市场商店,其中产品的“作者”将他们的时区以字符串格式存储在 usermeta 中,即Americas/Chicago.

我想用 UTC 偏移量而不是字符串输出每个用户的时区,以便我可以更轻松地操作它。我从另一个堆栈溢出问题中得到了下面的这个例子,但它在我的情况下不起作用。

$timezone = 'America/New_York'; //example string although I am getting the timezone from the database based on each users settings

if(!empty($timezone)) {
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone($timezone);
    $date = new DateTime( $newTZ );
    $date->setTimezone( $UTC);
    echo $date->format('H:i:s');
}

但是,此代码会破坏页面。无法理解为什么它会打破页面。我把它放到一个单独的函数中,它仍然会中断,错误日志也没有多大帮助。

日志说:

DateTime->__construct(Object(DateTimeZone))

标签: phpdatetimetimezone

解决方案


错误信息很清楚:

致命错误:未捕获的 TypeError:DateTime::__construct() 期望参数 1 为字符串,给定对象

DateTime. 因此,如果您想使用“now”,请传递“now”或null作为第一个参数。

$timezone = 'America/New_York'; //example string although I am getting the timezone from the database based on each users settings

if(!empty($timezone)) {
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone($timezone);
    $date = new DateTime(null, $newTZ );
    $date->setTimezone( $UTC);
    echo $date->format('H:i:s');
}

推荐阅读