Lumen 显示的时间与保存的时间不同 MYSQL DB

Lumen show different time than what is saved is MYSQL DB

我当前的时区是 Asia/Karachi,当我从 mysql 检索 table 数据时,它给了我(实际时间 - 5 小时)

例如:

mysql column value: '2021-04-21 01:34:57'

当我从 laravel DB::table('table_name')->get()->toArray();

检索时

it gives following :2021-04-20 20:34:57

并且更改我的时区也没有任何改变。

我还有什么遗漏的吗?

顺便说一句,我创建了以下路线来检查我当前的时区

$app->get('/timezone', function () {
    return date_default_timezone_get();
});

并且它给出了保存在我的环境中的相同内容,即(Asia/Karachi),但这不会改变我从 mysql 获得的结果,即使我将它更改为其他时区,如 Asia/Kolkata.

我尝试对此进行研究,但没有得到任何 suitable 答案。

https://dev.mysql.com/doc/refman/8.0/en/datetime.html

If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable.

据我所知,您需要考虑以下几点:

您的 Laravel/Lumen 应用的时区

这可以在 config/app.php -> timezone 中找到。

您的 MySQL 服务器的时区

您可以使用以下方式检索:

mysql> SELECT @@global.time_zone, @@session.time_zone;

服务器本身的时区

如果上面的mySQL查询returns SYSTEM,这意味着它使用系统时区设置,对于Debian/Ubuntu等你可以检查使用:

cat /etc/timezone

根据我的经验,您通常可以保持 system/mySQL 时区不变,只在 Laravel 配置中设置正确的时区。我知道这让我头疼,因为我第一次不得不弄清楚它是如何工作的。

我尝试了很多方法来解决这个问题,比如 添加环境变量 APP_TIMEZONE="Asia/Karachi"(无效) 我也尝试添加 DB_TIMEZONE="+05:00"(这在我的本地有效但不适用于暂存)

最后我在某个地方看到其他人有完全相同的问题来解决这个问题,他通过使用 carbon 增加时间来解决这个问题,这对我也很有效

'posted_at' => Carbon::parse($record->posted_at)->addHours(5)->toDateTimeString(),

我知道这不是最佳解决方案,但这是唯一有效的解决方案,所以我不得不接受它。