Laravel created_at 返回对象代替数据库中的日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47977423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:09:48  来源:igfitidea点击:

Laravel created_at return object in place of date format in database?

phpmysqllaravellaravel-5php-carbon

提问by Abhishek Badole

I am trying to return created_atdatetime from users table in JSON response in Laravel.

我试图created_at在 Laravel 的 JSON 响应中从用户表中返回日期时间。

In my databaes it show the value as 2016-07-18 00:00:00but when I try to return in JSON api it converts into

在我的数据库中,它显示的值是, 2016-07-18 00:00:00但是当我尝试以 JSON api 返回时,它会转换为

{
    date: "2016-07-18 00:00:00.000000",
    timezone_type: 3,
    timezone: "UTC"
}

How can I fix this problem?

我该如何解决这个问题?

采纳答案by Prashant Barve

You have Carbonin Laravel framework that helps you to make your datetime as you want with below code.

Carbon在 Laravel 框架中使用以下代码可以帮助您根据需要设置日期时间。

        $created_at = new Carbon($value)->toDateTimeString();

now pass $created_atat place of created_at. example code for users table (NOTE: not tested please check yourself that you need to pass an object or array)

现在通过$created_at的地方created_at。用户表的示例代码(注意:未测试请自行检查是否需要传递对象或数组)

        $user = User::find(1);
        $user->created_at = new Carbon($user->created_at)->toDateTimeString();

回答by Marcin Nabia?ek

By default created_atand updated_atare Carbonobjects, so you can do just:

默认情况下,created_at并且updated_atCarbon对象,因此您可以执行以下操作:

$object->created_at->toDateTimeString();

to get again in format Y-m-d H:i:s

再次获得格式 Y-m-d H:i:s

回答by YouneL

You can change that behavior by adding serializeUsingmethod In your AppServiceProviderclass to update the json serialization format of dates, it's only affect api calls (docs), here is an example:

您可以通过serializeUsing在您的AppServiceProvider类中添加方法来更改该行为以更新日期的 json 序列化格式,它仅影响 api 调用(docs),这是一个示例:

use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Carbon::serializeUsing(function ($carbon) {
            return $carbon->format('Y-m-d H:i:s');
        });
    }

    ...

}

回答by Alexey Mezenin

Since you want to get JSON response, you can use Eloquent API Resourceto transform Carbon object to any format, for example:

既然你想得到 JSON 响应,你可以使用Eloquent API Resource将 Carbon 对象转换为任何格式,例如:

return [
    'created_at' => $this->created_at->toDateTimeString(),
    ....
];