好的,我有以下代码
$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 时区(我使用的是 America/Vancouver),但它给了我一个奇怪的结果
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');
关于php - 在 PHP 中将 DateTime 字符串转换为不同的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10593576/