来自数据库的流明日期时区

Lumen date timezone from database

我在我的 env 文件中将我的时区从 UTC 更改为 Europe/Paris

当我创建 DateTime 时,时间是正确的(来自巴黎)。

$now = new \DateTime();
echo $now->format('Y-m-d H:i:s'); // correct

现在,在我的数据库 (MySQL) 中,我有一个时间戳字段,我得到时间 -1h :

// database value = 2022-01-31 13:35:42
$expired = new \DateTime($this->expired_at);
echo $expired->format('Y-m-d H:i:s'); // show 2022-01-31 12:35:42

为什么从数据库中获取的日期看起来像 UTC 而不是我的新时区?

在我的 PHP 项目中,我这样做:

SET @@global.time_zone = '+01:00';
SELECT @@global.time_zone, now();

当巴黎时间是 14:00 时 PHP 最后一次查询我得到:

@@global.time_zone => +01:00 
now() => 13:00 // instead of 14:00

MySQL 时区与 PHP 时区分开。它们是两个不同的应用程序。要在您的 PHP 代码中设置 MySQL 时区 运行 此 MySQL 查询:

SET @@global.time_zone = '+01:00';

为确保有效 运行 此查询:

SELECT @@global.time_zone, now();

根据评论编辑

如评论中所述,使用了 Laravel 框架。所以建议如下post: Is there any way I can set timezone in laravel 4 database.php configuration file?

Go to app->config->app.php in your Laravel directory. On line 43 you can >alter the default timezone to whatever you need.

'timezone' => 'Europe/Paris',