2013-02-28 192 views
0

我有一個用戶數據庫,每個用戶都有自己的時區設置。 例如,用戶A有GMT-05:00,用戶B有GMT + 1:00等時間/日期計算

我想使用我能找到的最簡單的方式顯示正確的當前日期/時間。我得到了這個代碼,儘管它看起來不錯(imho),但它顯示出正面的差異(+5小時)而不是負面的(減去5小時)。

腳本如下:

<?php 
    // below two lines -- info that I normally take from DB 
    $row['callstart'] = "1362067791"; // unixtimestamp 
    $userInfo['timezone'] = 'GMT-5'; 

    echo date('Y-m-d H:i:s',$row['callstart'])."\n"; // original hour 

    $date = date('Y-m-d H:i:s',$row['callstart']); 
    $date = new DateTime($date,new DateTimeZone('GMT')); 

    $date->setTimezone(new DateTimeZone($userInfo['timezone'])); 
    $row['callstart'] = $date->format('Y-m-d H:i:s'); 
    echo $row['callstart']; // converted to GMT-5 hour 
?> 

結果如下:

[email protected]:/tmp# php /work/yy.php 
    2013-02-28 16:09:51 // that's the current GMT hour/date 
    2013-02-28 21:09:51 // should actually be 11:09:51 instead of 21:09:51 
    [email protected]:/tmp# 

任何想法,和我在做什麼錯?

+0

賭博,並說你正在建立一個評級引擎? Feed是否具有時區偏移作爲規範的一部分,還是實際發送unixtimestamp?我問,因爲可能有更好的方式來做到這一點(在電信公司計費7年)。:) – Trent 2013-02-28 16:28:03

+0

是的,它的CDR數據庫(來源/目的地/通話時間)。所有通話時間均採用格林尼治標準時間,因爲客戶分佈在5-6個時區。系統日期是格林尼治標準時間,所以我沒有做任何時區偏移時,插入信息到數據庫(檢查$ row ['callstart']的價值,其正好16:09:51格林威治標準時間。 :是的,軟交換髮送的是unix時間戳記錄。 – Dan 2013-02-28 16:31:15

+0

狡猾的交換機:)大多數可尊重的提要會向您發送本地時間和服務器時間(或者至少是本地時間和UTC偏移量)。這就是說 - 這是你的數據庫插入腳本,還是你獲取unixtimestamp,然後即時顯示當地時間? – Trent 2013-02-28 16:39:09

回答

3

這就是常識作品對我們...從Wikipedia

In order to conform with the POSIX style, those zone names beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours ahead/east of GMT.)

因此,解決辦法是

// below two lines -- info that I normally take from DB 
$row['callstart'] = "1362067791"; // unixtimestamp 
// reversed the sign 
$userInfo['timezone'] = 'GMT+5'; 

echo date('Y-m-d H:i:s',$row['callstart'])."\n"; // original hour 

$date = date('Y-m-d H:i:s',$row['callstart']); 
$date = new DateTime($date,new DateTimeZone('GMT')); 

$date->setTimezone(new DateTimeZone($userInfo['timezone'])); 
$row['callstart'] = $date->format('Y-m-d H:i:s'); 
echo $row['callstart']; // converted to GMT-5 hour 
0

嗯...我寧願憂色這

<?php 



$row['callstart'] = "1362067791"; 
$userInfo['timezone'] = 'GMT-5'; 

$orginal =date('Y-m-d H:i:s',$row['callstart']); 
echo $orginal; 
echo '<br/>'; 

$newdate=date('Y-m-d H:i:s',($orginal + strtotime(substr($userInfo['timezone'] ,3).'hours'))); 
echo $newdate 

?> 

2013年2月28日17時09分51秒 2013年2月28日13時22分36秒

+0

嗨ddjikic,我不明白的幾件事。 1:爲什麼在一個unix時間戳上使用strtotime。 2. - 爲什麼在結果日期使用substr? ==我刪除了strtotime語句並運行了你的例子,得到了結果1970-01-01 00:00:00,這不是一個好日子 – Dan 2013-02-28 16:38:42

+0

對不起,我有一個substr錯誤,不需要第三個參數 – ddjikic 2013-02-28 16:43:28