PHP时区功能不起作用

时间:2011-08-25 10:09:31

标签: php mysql timezone

我正在创建一个论坛,该论坛还会存储发送帖子的时间,我需要将其转换为用户的时区。
现在,MySQL DataBase用UTC_TIMESTAMP()(在DATETIME类型的列中)存储时间,然后我从http://www.ultramegatech.com/blog/2009/04/working-with-time-zones-in-php/上的代码创建了一个小函数来将时间转换为用户的时区。这是功能:

function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
    // timestamp to convert
    $timestamp = strtotime($timestamp);
    // the time formatting to use
    $format = $format;
    // the time zone provided
    $tz = $tz;

    // create the DateTimeZone object for later
    $dtzone = new DateTimeZone($tz);

    // first convert the timestamp into an RFC 2822 formatted date
    $time = date('r', $timestamp);

    // now create the DateTime object for this time
    $dtime = new DateTime($time);

    // convert this to the user's timezone using the DateTimeZone object
    $dtime->setTimeZone($dtzone);

    // print the time using your preferred format
    $time = $dtime->format($format);

    return $time;
}

我在http://assets.momo40k.ch/timezones.php做了一个测试页
现在,当我在我的时区(11:50)中插入一个帖子到数据库时,Europe/Rome,它会在UTC中插入09:50,这是正确的,根据一些在线时区转换器。
但是当我尝试使用Europe/Rome函数将其转换回convertTZ()时,它会返回09:50,就好像Europe/Rome是UTC一样。如果我尝试将其转换为GMT + 2:00时区,则会返回10:50。任何人都可以弄清楚为什么会这样吗?

P.S:我没有使用CONVERT_TZ() SQL函数,因为我的服务器不支持命名时区,所以这个函数是我的解决方法。

2 个答案:

答案 0 :(得分:1)

确保您存储的时间戳为UTC:

$date = new DateTime($timestamp, new DateTimeZone("UTC"));
$date->format(DATE_W3C); // does it gives the expected result ?

BTW你的功能可以简化为:

function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
    $dtime = new DateTime($timestamp, new DateTimeZone("UTC"))
    $dtime->setTimezone(new DateTimeZone("UTC"));
    return $dtime->format($format);
}

答案 1 :(得分:1)

MySQL总是在内部以UTC格式存储TIMESTAMP字段(实际上是unix时间戳的定义)。因此,当您进行SELECT或UPDATE / INSERT / REPLACE时,您获取或设置的时间始终位于MySQL服务器的本地时区。

所以常见的错误是存储UTC_TIMESTAMP(),MySQL将其解释为本地时间,因此当它在内部作为unix TIMESTAMP存储在内部时,当前时间会被双重转换为UTC。