2012-05-15 44 views
2

確定我有這個以下代碼在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 

我哪裏出錯了?

回答

7

你讓事情太難了。要在時區之間進行轉換,您只需使用適當的源時區創建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'); 
+0

是的,謝謝你,對不起,我試圖在困難的方式自己做事情 –

1

看起來您需要減去偏移量,而不是將其添加到我,從快速瀏覽結果。它是有道理的:說你在格林威治標準時間-5,你想把你的時間轉換爲格林威治標準時間。你不會減去5小時(時間+偏移量),你會增加5小時(時間偏移量)。當然,我很累,所以我可能會反思。

+0

我試過了..當我減去它的正確與UTC的偏移量,但問題是當我做了像亞洲/馬尼拉>美國/溫哥華他們變得一樣 –

+0

你的意思是他們加起來是0嗎?如果是這樣,您需要先通過UTC或將原始時區的偏移量添加到目標時區的偏移量。從我所知道的情況來看,你的代碼只是得到UTC的偏移量,所以當你做UTC-8 - > UTC + 8時,你最終會得到時間減去本身。 – demize

1

不要使用和的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:我:■」 將採用當前本地時區(從php.ini中或你的ini_set),以顯示它與時區,你可以使用格式「c」或「r」