php - 如何处理服务器时间和用户本地时间之间的差异?

标签 php codeigniter datetime

我正在开发面向其他国家/地区的 Web 应用程序。

现在,为了说明我的想法,我在想这样的事情:

// Illustrates the current time on my server
$time = new DateTime();
echo $time->format("Y-m-d H:i:s P");

// Illustrates the current time for the time the user told my app he is in
$time = new DateTime(null, new DateTimeZone('Europe/London'));
echo $time->format("Y-m-d H:i:s P");

这个的输出是:

2012-11-30 11:02:40 +01:00 // My server time
2012-11-30 10:02:40 +00:00 // The users time

一切都很好,因为我现在可以为用户显示当前时间。但我需要的是获取用户输入并将其转换为我的服务器时间 - 或者至少我认为这是正确的方法。

一个用例
伦敦的用户告诉我的应用程序他需要在 2012-12-01 19:00:00 执行操作。通过在我的数据库中更新这个时间戳,我的 cronjob 将在指定的时间执行这个操作。但是我的用户会体验到这种情况发生在 2012-12-01 18:00:00

在考虑解决此问题的方法时,我工作了一些偏移时间,这给我带来了很多意大利面条式代码和一些困惑的数据库表设计。

我怎样才能做到这一点,让它有意义?

最佳答案

您可以将 DateTime 对象的时区更改为所需的时区。如果您有用户指定的时区日期时间,您可以轻松进行转换。

 $time = new DateTime(null, new DateTimeZone('Europe/London'));
 echo $time->format("Y-m-d H:i:s P");

 $time->setTimezone(new DateTimeZone('America/Chicago'));
 echo $time->format("Y-m-d H:i:s P");

关于php - 如何处理服务器时间和用户本地时间之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643106/

相关文章:

php - Yii2 从整数转换为日期时间以显示并用整数保存到数据库中

php - 传感器数据直播

php - 如何通过PHP执行批处理文件?

PHP MySQLi 错误处理 1062 重复键输入

javascript - 在 ajax 处理期间,当我们在弹出窗口外单击时,不应关闭弹出窗口

php - 代码点火器 2.1.3 : sess_destroy() causes Undefined index: session_id etc notice when 'sess_use_database' == TRUE

datetime - 如何从 IronPython 日期时间转换为 .NET 日期时间?

ini 文件中的 PHP SQLite 信息

php - 如何确定 'Codeigniter' 中执行查询的状态?

sql - 将日期时间转换为日期字符串 2019-05-02 12 :00:00 to 2019-05-02