【发布时间】:2011-11-03 13:15:10
【问题描述】:
我正在创建一个论坛,该论坛还存储帖子的发送时间,我需要将其转换为用户的时区。
现在,MySQL 数据库用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做了一个测试页。
现在,当我在我的时区(即Europe/Rome)的11:50 处将帖子插入数据库时,它会在UTC 中插入09:50,这是正确的,根据一些在线时区转换器。
但是当我尝试使用convertTZ() 函数将其转换回Europe/Rome 时,它返回09:50,好像Europe/Rome 是UTC。如果我尝试将其转换为 GMT+2:00 时区,它会返回 10:50。谁能猜出这是为什么?
P.S:我没有使用CONVERT_TZ()SQL函数,因为我的服务器不支持命名时区,所以这个函数是我的解决方法。
【问题讨论】: