2013-02-28 193 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