我一直在使用 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 上对此进行了测试,但结果可能因服务器配置而异。
最佳答案
The current user's timezone has been set with date_default_timezone_set() How do I get the it's GMT +- time?
你不能。由于夏令时的变幻莫测,偏移量不是恒定的——它会根据日期而变化。
使用gmmktime()
(连同一些字符串解析)将 GMT 日期/时间转换为 UNIX 时间戳,然后使用 date()
在当前时区显示。
关于php - 获取时区 GMT 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13559703/