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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了在PHP中将DateTime字符串转换为不同的时区脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
好吧,我有以下代码

$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时区(我使用美国/温哥华)但它给了我一个奇怪的结果

而对于美国/温哥华

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');

脚本宝典总结

以上是脚本宝典为你收集整理的在PHP中将DateTime字符串转换为不同的时区全部内容,希望文章能够帮你解决在PHP中将DateTime字符串转换为不同的时区所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。