获取格林威治标准时间的时区?

时间:2012-11-26 06:28:20

标签: php mysql date

我一直在使用DATETIME列在我的数据库中存储用户消息。我需要向不同国家/地区的用户显示消息的发送时间,因为数据库使用GMT + 0我需要将检索到的时间调整到用户的时区。

当前用户的时区已设置为date_default_timezone_set()如何获取GMT + - 时间?

修改

遵循@doniyor的想法,这就是我所做的:

 // Get server hour
$localtime = localtime();
$serverHour = $localtime[2]; # The server's timezone is used by default before defining one

// Set timezone
date_default_timezone_set('user's timezone goes here');

// Get user hour
$localtime = localtime(); # Now localtime gives the user's time since timezone has been changed
$userHour = $localtime[2];
$timeAdjustment =  $userHour - $serverHour < -12 ? 24 + $userHour - $serverHour : $userHour - $serverHour; // Calculate hours to add to rows got from db to match user's time

// Example of a row adjusted to match user's time
    $adjustTime =  ($userHour - $serverHour < -12 ? 24 + $userHour - $serverHour : ($userHour - $serverHour > 12 ? $userHour - $serverHour - 24 : $userHour - $serverHour)*60*60; // strtotime is in seconds so $timeAdjustment needs *60*60 to convert to seconds too

我在PHP5 + Apache上测试了这个,但结果可能因服务器配置而异。

3 个答案:

答案 0 :(得分:1)

  

当前用户的时区已设置为date_default_timezone_set()如何获取GMT + - 时间?

你做不到。由于夏令时的变幻莫测,偏移量不是恒定的 - 它可以根据日期而改变。

使用gmmktime()(连同一些字符串解析)将GMT日期/时间转换为UNIX时间戳,然后使用date()在当前时区显示。

答案 1 :(得分:1)

只需将日期值的值作为UNIX时间戳传递给JavaScript。例如,使用AJAX:

echo json_encode(array(
    'time' => strtotime($row['msg_time']),
    'msg' => 'hello world',
));

然后,使用Date()将其转换为用户的本地时间:

var msgTime = new Date(data.time * 1000);

答案 2 :(得分:0)

如果错了,请不要downvote :)

如果您在客户端浏览器中获得时区时间并检查差异,如果存在差异,则根据客户端的位置添加或减去此差异值。

相关问题