我有一个用户数据库,每个用户都有自己的时区设置。 例如,用户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
?>
以下结果:
root@ssw238:/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
root@ssw238:/tmp#
知道我在哪里做错了什么?
答案 0 :(得分: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
答案 1 :(得分: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-02-28 17:09:51 2013-02-28 13:22:36