2012-11-26 110 views
0

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

当前用户的时区已设置为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的,但可能的结果取决于服务器的配置。

+0

尝试使用Unix的时间戳,然后将其转换为日期 – Andrew

+0

它使用的只是网页建立日期时间,所以可能如果我改变时间戳我会得到很多错误 – lisovaccaro

回答

0

如果错了,请不要:) downvote

如果你在客户端浏览器时区时间和检查的差异,如果有差异,然后添加或根据。减去在客户端的位置,这个差值。

+0

你的意思是比较我的服务器和用户的时间?这将工作,但我不知道如何获得数据库/服务器用来比较它与用户的当前时间 – lisovaccaro

+0

还必须有一些像get_server_time()函数,我在路上,现在不能谷歌:D – doniyor

+0

我浏览了一下,但找不到这样的功能,但是我发现只是在设置用户的时区之前花时间使用服务器的默认时区来有效地获取服务器的时间。所以我只是在设置时区之前得到它,然后再获取用户的时间。我接受了答案并复制了代码。 – lisovaccaro

1

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

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

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

1

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

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

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

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