如何使用 Carbon 从 "created_at" 中提取时间
How to extract the time from "created_at" with Carbon
我仍在努力使用 Laravel 框架中的 Carbon 功能。我创建了这些在我的模型中使用的函数来提取表中 "created_at" 字段的日期:
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y');
}
这适用于日期,但我需要如何在此模型中编写一个函数,它只提取 created_at 字段中的时间?
$model->created_at
这将使用一些 Eloquent 魔法和 return 创建日期作为 Carbon 对象。
我觉得您在重写日期的默认行为方面限制了自己很多。
如果删除访问器 (getCreatedAtAttribute
),您将能够从 属性 本身调用格式,即
$model->created_at->format('d.m.Y')
或
$model->created_at->format('H:i:s');//e.g. 15:30:00
Carbon
只是 DateTime
的包装。您可以在此处查看格式字符列表:http://php.net/manual/en/function.date.php
例如今天的日期是 2016 年 2 月 6 日 jS F Y
尝试使用
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('H:i:s');
}
输出时间
如果您想手动将日期插入数据库,您可以这样做。
"created_at" => now(),
"updated_at" => now()
调试
dd(now());
// output
// 2022-03-16 10:24:07
我仍在努力使用 Laravel 框架中的 Carbon 功能。我创建了这些在我的模型中使用的函数来提取表中 "created_at" 字段的日期:
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y');
}
这适用于日期,但我需要如何在此模型中编写一个函数,它只提取 created_at 字段中的时间?
$model->created_at
这将使用一些 Eloquent 魔法和 return 创建日期作为 Carbon 对象。
我觉得您在重写日期的默认行为方面限制了自己很多。
如果删除访问器 (getCreatedAtAttribute
),您将能够从 属性 本身调用格式,即
$model->created_at->format('d.m.Y')
或
$model->created_at->format('H:i:s');//e.g. 15:30:00
Carbon
只是 DateTime
的包装。您可以在此处查看格式字符列表:http://php.net/manual/en/function.date.php
例如今天的日期是 2016 年 2 月 6 日 jS F Y
尝试使用
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('H:i:s');
}
输出时间
如果您想手动将日期插入数据库,您可以这样做。
"created_at" => now(),
"updated_at" => now()
调试
dd(now());
// output
// 2022-03-16 10:24:07