laravel 如何使用 Carbon 从“created_at”中提取时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42071525/
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
How to extract the time from "created_at" with Carbon
提问by sesc360
I am struggling with the Carbon functionalities within Laravel framework still. I created these functions used in my model to extract the date of the "created_at" field in my tables:
我仍在为 Laravel 框架中的 Carbon 功能而苦苦挣扎。我创建了这些在我的模型中使用的函数来提取表中“created_at”字段的日期:
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y');
}
This works fine for the date, but how would I need to write a function in this model, that will extract only the time within the created_at field?
这适用于日期,但是我如何需要在这个模型中编写一个函数,它只会提取 created_at 字段中的时间?
回答by Rwd
I feel like you're limiting yourself a lot be overriding the default behaviour for dates.
我觉得你限制了自己,覆盖了日期的默认行为。
If you remove your accessor (getCreatedAttribute
) you'll be able to call format from the property itself i.e.
如果您删除访问器 ( getCreatedAttribute
),您将能够从属性本身调用格式,即
$model->created_at->format('d.m.Y')
or
或者
$model->created_at->format('H:i:s');//e.g. 15:30:00
Carbon
is just a wrapper for DateTime
. For a list of format characters you can look here: http://php.net/manual/en/function.date.phpe.g. todays date as 6th February 2016 would be jS F Y
Carbon
只是DateTime
. 有关格式字符列表,您可以在此处查看:http: //php.net/manual/en/function.date.php例如今天的日期为 2016 年 2 月 6 日将是jS F Y
Hope this helps!
希望这可以帮助!
回答by Junaid
try to use
尝试使用
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('H:i:s');
}
output will be time
输出将是时间
回答by AngryUbuntuNerd
$model->created_at
This will use some Eloquent magic and return the creation date as a Carbon object.
这将使用一些 Eloquent 魔法并将创建日期作为 Carbon 对象返回。