[英]Converting DateTime String to Different Timezones in 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);
$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 > UTC 2012-05-15 19:50:00 = the correct is 2012-05-15 02:50
而对于美国/温哥华
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');
不要使用getOffset并自己计算,你应该使用setTimezone进行显示
<?php
function conv($fromTime, $fromTimezone, $toTimezone) {
$from = new DateTimeZone($fromTimezone);
$to = new DateTimeZone($toTimezone);
$orgTime = new DateTime($fromTime, $from);
$toTime = new DateTime($orgTime->format("c"));
$toTime->setTimezone($to);
return $toTime;
}
$toTime = conv("2012-05-15 10:50:00", "Asia/Manila", "UTC");
echo $toTime->format("Y-m-d H:i:s");
// you can get 2012-05-15 02:50:00
echo "\n";
$toTime = conv("2012-05-16 02:50:00", "Asia/Manila", "America/Vancouver");
echo $toTime->format("Y-m-d H:i:s");
// you can get 2012-05-15 11:50:00
echo "\n";
格式“Ymd H:i:s”将使用当前本地时区(来自php.ini或您的ini_set),以时区显示,您可以使用格式“c”或“r”
看起来您需要减去偏移量而不是将其添加到我身上,快速浏览一下结果。 这是有道理的:说你在GMT-5中,你想把你的时间转换成GMT。 你不会减去5小时(时间+偏移),你会增加5小时(时间 - 偏移)。 当然,我相当累,所以我可能会倒退。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.