php - 使用 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))
解决方案
错误信息很清楚:
致命错误:未捕获的 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');
}
推荐阅读
- maven - 从 springtestdbunit 收集依赖项失败
- c# - 从集合对象中获取属性值
- javascript - Google Drive 是否限制了我使用 Javascript 进行的音频复制?
- eclipse - STS java文件编辑器错误悬停文本设置
- django - Django - 管理命令 - Pandas read_csv - 本地主机工作 - Heroku
- mysql - 尝试通过选择删除时发生错误 #1241 - 操作数应包含 1 列
- javascript - 如何在 Angular 7 中加快上传速度?
- elasticsearch - 在 Logstash 级别读取 CSV 并根据提取的数据进行过滤
- c# - 在 Visual Studio 中处理多个项目
- xml - 如何创建通过读取 wpf 中的 xml 文件动态创建的按钮的单击事件?