[英]Converting Timezone String to UTC offset using PHP
我有一个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))
错误消息非常清楚:
致命错误:未捕获的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');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.