$ model-> get()上带有雄辩模型时间戳记的时区错误,但使用print_r()纠正 [英] Wrong timezone with Eloquent Model timestamps on $model->get(), but correct with print_r()
问题描述
对于任何使用Laravel 7的雄辩模型,我都感到有些奇怪!
I am experiencing something quite weird for any Eloquent Model with Laravel 7!
P.S .:我已经进行了所有测试:
P.S.: I've run on every test I did:
php artisan optimize:clear
我不知道我在这里想念什么!
I don't know what I am missing here!
我不会发布任何代码,因为这是带有模型绑定的简单CRUD.
I won't post any code because that's a simple CRUD with Model Bindings.
在保存created_at和updated_at字段时,它会以我的timezome"America/Sao_Paulo"正确保存在MySQL中.
When saving the created_at and updated_at fields, it is correctly saved in the MySQL with my timezome "America/Sao_Paulo".
但是,如果我在任何控件中执行此操作:
But if I do this in any controler:
return $model->get()
或
return $model->paginate()
或
Model::all()
我得到答复:
{
"data": [
{
... other fields
"created_at": "2020-08-23T15:22:41.000000Z",
"updated_at": "2020-08-23T15:22:41.000000Z"
}
]
}
它返回的错误时间是+1小时.
And it returns the wrong time with +1 hour.
但是,在这里事情变得很奇怪...如果我用print_r()中的任何一个,我都会得到正确的时间!
However, here is where things get weird... if I print_r() any of them, I get the corret time!
Array
(
... other fields
[created_at] => 2020-08-23 12:22:41
[updated_at] => 2020-08-23 12:22:41
)
我尝试使用:
public function getDateFormat()
{
return 'Y-m-d H:i:s';
}
但没有效果!
预先感谢!
推荐答案
Laravel 7 使用新的日期序列化格式在具有 UTC
在 Laravel 7 之前,日期将被序列化为以下格式:
Before Laravel 7, dates would be serialized to a format like the following :
2019-12-02 20:01:00
使用 ISO-8601 格式序列化的日期将显示为:
Dates serialized using the ISO-8601 format will appear like :
2019-12-02T20:01:00.283041Z
请注意, ISO-8601 日期始终以 UTC 表示.
如果您想继续使用以前的行为,可以在模型上覆盖 serializeDate()
方法:
If you would like to keep using the previous behavior you can override the serializeDate()
method on your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
在此处
这篇关于$ model-> get()上带有雄辩模型时间戳记的时区错误,但使用print_r()纠正的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!