2011-03-29 32 views
1

我正在創建一個腳本,允許用戶選擇他們自己的時區... 並輸入日期$ time..So用戶輸入的日期/時間必須轉換爲GMT格式,同時存儲到數據庫中。 從數據庫中檢索時,應該再次轉換爲原始格式。 這裏也必須包含DST概念。如何編寫一個函數來獲取不同的時區在php中?

所以這裏日期是它可以是一個字符串或數組(多維數組也) 所以我想這樣的一個變量.....

function ConvertOneTimezoneToAnotherTimezone($time,$currentTimezone,$timezoneRequired) 
{ 

    $current_zone = new DateTimeZone($currentTimezone); 
    //$gmt = new DateTimeZone('GMT'); 

    $date = new DateTime($time, $current_zone); 
    //$date->setTimezone($gmt); 
    $date->setTimezone(new DateTimeZone($timezoneRequired)); 

    return $date->format('Y-m-d H:i:s'); 

// Convert it back to Original timezone 
    $date->setTimezone($current_zone); 
    return $date->format('Y-m-d H:i:s'); 
} 

$time='2011-03-29 11:15:00.000'; 

echo "Current Date/Time is=".ConvertOneTimezoneToAnotherTimezone($time,'Asia/Kolkata','America/New_York'); 

但在這裏,我只能轉換爲不同的時區,但我想它轉換日期/時間,也同時檢索給原始格式...... 請人幫我一個單一的功能......

+1

你能提供你的預期產出嗎?您在第一個setTimeZone之後從函數返回,所以您將永遠不會到達第二個。你是說你想要從$ date-> format()調用中獲取值嗎? – 2011-03-29 06:15:15

+0

雅我希望輸出作爲轉換日期/時間= 2011-12-28 07:22:00 原始日期/時間2011-12-28 17:52:00。這個日期可以在一個數組或它也可以是一個串。 – 0001 2011-03-29 06:18:01

回答

0
+0

該鏈接已死,這就是爲什麼只包含鏈接的答案[被認爲是不好的做法](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-好的答案) – GSee 2012-07-15 23:30:56

+0

謝謝,我把正確的鏈接...順便說一句,由誰認爲不好的做法? – Wh1T3h4Ck5 2012-07-16 00:51:39

+0

我的評論中嵌入了一個鏈接。這裏的鏈接再次http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – GSee 2012-07-16 00:52:32

0
<?php 

function ConvertOneTimezoneToAnotherTimezone($originalDateTime, $originalTimeZone, $targetTimeZone) { 
    $format = 'Y-m-d H:i:s'; 

    $dateTime = new DateTime($originalDateTime, new DateTimeZone($originalTimeZone)); 
    $original = $dateTime->format($format); 

    $dateTime->setTimezone(new DateTimeZone($targetTimeZone)); 
    $target = $dateTime->format($format); 

    return compact('original', 'target'); 
} 

$dateTime = '2011-03-29 11:15:00.000'; 
$converted = ConvertOneTimezoneToAnotherTimezone($dateTime,'Asia/Kolkata','America/New_York'); 

echo sprintf('Original Date/Time is=%s', $converted['original']), PHP_EOL; 
echo sprintf('Converted Date/Time is=%s', $converted['target']), PHP_EOL; 
+0

確定thankx wilmoore.your代碼工作正常.... ....但函數內只有我需要檢查的條件,其中日期可以是一個數組值或它也可以是一個字符串,根據我只需要顯示兩個日期。 – 0001 2011-03-29 06:41:35

相關問題