使用PHP

时间:2018-12-31 19:42:37

标签: php datetime timezone

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

我想用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))

1 个答案:

答案 0 :(得分:2)

错误消息非常清楚:

  

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

DateTime的时区为 second 参数。因此,如果您想使用“现在”,则可以传递“现在”或将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');
}