Laravel 的时间戳有奇怪的返回格式

标签 laravel api axios laravel-api

我有一个帖子模型和 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"
    }
  ]

如您所见,在 PHPMyAdmin 中一切都很好: enter image description here

最佳答案

这并不“奇怪”。非常标准ISO8601 format具有微秒精度和“Z”(即 UTC)时区名称。 ISO8601 格式允许在日期和时间部分之间使用“T”,以及其他几种变体。

数据库显示碰巧使用了不同的变体。这是正常的并且符合预期,因为数据库类型是 DATETIME (或类似类型),因此显示的文本只是给定的表示形式。两种表示法都代表相同的日期和时间^。

这是一种传输信息的良好格式(在 JSON 序列化中很常见),但不太适合向用户显示。

^ 假设数据库中的数据是从 UTC 源存储的,这里的情况就是这样。如果它是本地时间源,则会出现其他复杂情况,因为如果不调整值,JSON 中的“Z”偏移量将不正确/具有误导性。

关于Laravel 的时间戳有奇怪的返回格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62123165/

相关文章:

ruby-on-rails - Rails Grape API 'id is invalid' 在不需要 id 的请求中

php - Eloquent multiple where from date 字段 <= >=

php - laravel - 谷歌分析 API 身份验证

laravel - 如何在 Laravel 5.2.* 或更高版本中使用 setasign fpdi v2.0.0?

php - Google_Service_Directory - (403) 无权访问此资源/api

javascript - 在axios中增加maxContentLength和maxBodyLength

javascript - Passport deserializeUser() 永远不会通过 Axios http 请求调用

MobX 中的 Ajax 调用 : MobX observer: Store is not available! 确保它是由某个 Provider 提供的

其他存储库中的 Laravel 存储库

laravel - 依赖注入(inject)在 Laravel 5.2 的迁移文件中不起作用