加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中将DateTime字符串转换为不同的时区

发布时间:2020-12-13 22:03:39 所属栏目:PHP教程 来源:网络整理
导读:好吧,我有以下代码 $from = "Asia/Manila";$to = "UTC";$org_time = new DateTime("2012-05-15 10:50:00");$org_time = $org_time-format("Y-m-d H:i:s");$conv_time = NULL;$userTimezone = new DateTimeZone($from);$gmtTimezone = new DateTimeZone($to);
好吧,我有以下代码

$from = "Asia/Manila";
$to = "UTC";
$org_time = new DateTime("2012-05-15 10:50:00");
$org_time = $org_time->format("Y-m-d H:i:s");
$conv_time = NULL;

$userTimezone = new DateTimeZone($from);
$gmtTimezone = new DateTimeZone($to);
$myDateTime = new DateTime($org_time,$gmtTimezone);
$offset = $userTimezone->getOffset($myDateTime);
$conv_time = date('Y-m-d H:i:s',$myDateTime->format('U') + $offset);
echo $conv_time;

使用此代码我想将2012-05-15 10:50:00转换为UTC和-8时区(我使用美国/温哥华)但它给了我一个奇怪的结果

06001

而对于美国/温哥华

Asia/Manila > America/Vancouver 
2012-05-16 02:50:00 = the correct is 2012-05-14 19:50

哪里出错了?

解决方法

你太过刻苦了.要在时区之间进行转换,您需要做的就是使用正确的源时区创建DateTime对象,然后通过setTimeZone()设置目标时区.

$src_dt = '2012-05-15 10:50:00';
$src_tz =  new DateTimeZone('Asia/Manila');
$dest_tz = new DateTimeZone('America/Vancouver');

$dt = new DateTime($src_dt,$src_tz);
$dt->setTimeZone($dest_tz);

$dest_dt = $dt->format('Y-m-d H:i:s');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读