0

我有一个用户数据库,每个用户都有自己的时区设置。例如,用户 A 有 GMT-05:00 ,用户 B 有 GMT+1:00 等

我正在尝试使用我能找到的最简单的方式为这些用户显示正确的当前日期/时间。我得到了这段代码,虽然它看起来不错(恕我直言),但它显示了正的差异(+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#

知道我在哪里做错了吗?

4

2 回答 2

3

这是常识对我们不利的时候......来自维基百科

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
于 2013-02-28T16:40:28.390 回答
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

于 2013-02-28T16:34:27.547 回答