在PHP中将日期时间字符串转换为不同的时区

在PHP中将日期时间字符串转换为不同的时区,php,datetime,timezone,Php,Datetime,Timezone,好的,我有以下代码 $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); $myDate

好的,我有以下代码

$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

我哪里出错了?

从快速浏览结果看,似乎您需要减去偏移量,而不是将其添加到我身上。这是有道理的:假设你在GMT-5,你想把你的时间转换成GMT。你不会减去5小时(时间+偏移量),而是加上5小时(时间-偏移量)。当然,我很累,所以我可能在想问题。

你把事情弄得太难了。要在时区之间进行转换,只需创建一个具有正确源时区的
DateTime
对象,然后通过
setTimeZone()
设置目标时区


不要用getOffset自己计算,应该用它来显示

<?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";

我试过了。。当我用UTC减去偏移量时,它是正确的,但问题是当我做一些类似于亚洲/马尼拉>美洲/温哥华的事情时,它们变成了sameDo,你的意思是它们加起来等于0?如果是这样,您需要先通过UTC,或者将原始时区的偏移量添加到目标时区的偏移量中。据我所知,您的代码只得到UTC的偏移量,因此当您执行UTC-8->UTC+8时,您将得到时间减去自身的时间。是的,谢谢,很抱歉,我试图以一种艰难的方式实现自己的目标
$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
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";