我有一个帖子模型和 Controller ,当我尝试获取所有帖子时,它返回created_at和updated_at列,如下所示:
“created_at”:“2020-05-31T22:04:38.000000Z”,
如您所见,日期和时间之间有一个奇怪的“T”+末尾有“.000000Z”。
我尝试使用Carbon::setToStringFormat();
但没有运气。
这是我的 PostsController@index
{
Carbon::setToStringFormat(DateTime::ISO8601);
$posts = Post::with('author:id,name,lastName')->get();
return response()->json(['posts' => $posts->toArray()],200);
}
这个问题在我所做的每个模型/迁移中都存在。包括用户表。
"users": [
{
"id": 1,
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c1c4cdc9cee0d4c5d3d48ec3cfcd" rel="noreferrer noopener nofollow">[email protected]</a>",
"status": "admin",
"name": "Administrators",
"lastName": "Uzvārds",
"department": "client",
"phone": "null",
"created_at": "2020-05-31T22:03:36.000000Z",
"updated_at": "2020-05-31T22:03:36.000000Z"
},
{
"id": 2,
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="106563756250647563643e737f7d" rel="noreferrer noopener nofollow">[email protected]</a>",
"status": "employee",
"name": "Darbinieks",
"lastName": "Uzvārds",
"department": "client",
"phone": "null",
"created_at": "2020-05-31T22:03:36.000000Z",
"updated_at": "2020-05-31T22:03:36.000000Z"
}
]
最佳答案
这并不“奇怪”。非常标准ISO8601 format具有微秒精度和“Z”(即 UTC)时区名称。 ISO8601 格式允许在日期和时间部分之间使用“T”,以及其他几种变体。
数据库显示碰巧使用了不同的变体。这是正常的并且符合预期,因为数据库类型是 DATETIME (或类似类型),因此显示的文本只是给定的表示形式。两种表示法都代表相同的日期和时间^。
这是一种传输信息的良好格式(在 JSON 序列化中很常见),但不太适合向用户显示。
^ 假设数据库中的数据是从 UTC 源存储的,这里的情况就是这样。如果它是本地时间源,则会出现其他复杂情况,因为如果不调整值,JSON 中的“Z”偏移量将不正确/具有误导性。
关于Laravel 的时间戳有奇怪的返回格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62123165/