php - 获取时区 GMT 时间?

标签 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 上对此进行了测试,但结果可能因服务器配置而异。

最佳答案

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/

相关文章:

PHP 服务器。我应该在启动时下载应用程序内容吗

php - 如何使用简码在内容中包含 wordpress 帖子的页面标题

mysql - 选择特定用户 ID 的所有项目和任务

php - 将图像作为 BLOB 或某处的普通文件存储在 mysql 中的内存效率更高吗?

mysql - 使用数组在两个日期之间插入

php - 如何在 .htpasswd 文件中设置密码

MySQL - 我可以在实际的插入查询本身中使用即将成为 insert_id 吗?

javascript - 获取/检测 div 元素内容更改的日期和时间

java - 为什么我的 GregorianCalendar 对象返回错误的星期几?

php - Ajax php/mysql 在非常活跃的提要上加载更多按钮