5

好的,我有以下代码

$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

我哪里出错了?

4

3 回答 3

11

你让事情变得太难了。要在时区之间进行转换,您需要做的就是创建一个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');
于 2012-05-15T03:17:23.483 回答
2

不要用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"

于 2012-05-15T03:23:09.657 回答
1

快速浏览一下结果,您似乎需要减去偏移量而不是将其添加给我。这是有道理的:假设您在 GMT-5 并且您想将您的时间转换为 GMT。您不会减去 5 小时(时间 + 偏移量),而是会增加 5 小时(时间 - 偏移量)。诚然,我很累,所以我可能会倒退。

于 2012-05-15T02:56:16.843 回答