简体   繁体   English

如何将碳转换为字符串,仅取日期?

[英]How to convert a carbon into string, to take the date only?

i have an collection like this我有一个这样的收藏

0 => array:4 [
  "so" => "SO-1"
  "product_name" => "EXTREME FORTE - BP"
  "created_at" => Carbon @1527481346 {#628
    date: 2018-05-28 04:22:26.0 UTC (+00:00)
  }
  "id" => "5b0b84027475aa1508002623"
]

how to take the "2018-05-28" only?如何只取“2018-05-28”? can somebody help me to fix this problem?有人可以帮我解决这个问题吗? thank's anyway不管怎么说,还是要谢谢你

$collection_item->created_at->format('Y-m-d');

i prefere this我更喜欢这个

$model_item->created_at->toDateString();

since all date fields that located in protected $dates array in the modal is type of \\Carbon\\Carbon .因为位于模式中protected $dates array中的所有日期字段都是\\Carbon\\Carbon类型。

so the above code could apply to any date field as long as you declared it as date in $dates array in the modal as follow所以上面的代码可以应用于任何日期字段,只要你在模态中的$dates array中将其声明为日期,如下所示

// this includes created_at and updated_at by default so no need to add it 
protected $dates = ['approved', 'seen_at'];

It is also possible to add automatic casting to your model, for example :还可以为您的模型添加自动铸造,例如:

protected $casts = [
    'created_at' => 'date:Y-m-d',
    'updated_at' => 'datetime:Y-m-d H:00',
];

Remark : your mileage may vary depending on your Laravel version备注:您的里程可能因您的 Laravel 版本而异

https://laravel.com/docs/8.x/eloquent-mutators#date-casting https://laravel.com/docs/8.x/eloquent-mutators#date-casting

https://laravel.com/docs/8.x/eloquent-serialization#date-serialization https://laravel.com/docs/8.x/eloquent-serialization#date-serialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM