Laravel实战笔记

Laravel中默认时间格式为:"updated_at": "2024-05-14T03:16:43.000000Z"

Date

要修改 Laravel 模型中 updated_at 字段的输出格式,可以通过以下两种方式实现:

  1. 使用 toDateString() 方法:
$user = User::find(1);
$updatedAt = $user->updated_at->toDateString(); // 输出: "2024-05-14"
  1. 在模型中自定义 updated_at 属性的访问器:
class User extends Model
{
    public function getUpdatedAtAttribute($value)
    {
        return date('Y-m-d', strtotime($value));
    }
}

$user = User::find(1);
$updatedAt = $user->updated_at; // 输出: "2024-5-14"

第一种方式直接使用 toDateString() 方法,这个方法会将 updated_at 字段转换为 "YYYY-MM-DD" 格式的日期字符串。

第二种方式是在模型中定义一个访问器 (Accessor) 方法,通过 getUpdatedAtAttribute() 方法来自定义输出格式。在这个例子中,我们使用 date('Y-m-d', strtotime($value)) 将原始的 updated_at 值转换为 "YYYY-m-d" 格式的日期字符串。

无论使用哪种方式,最终输出的 updated_at 字段都会是您想要的格式。如果您还有其他问题,欢迎继续提问。

Datetime

好的,如果您需要将 Laravel 模型中的 updated_at 字段格式化为完整的日期时间格式,比如 "YYYY-MM-DD HH:mm:ss",可以使用以下方法:

  1. 使用 toDateTimeString() 方法:
$user = User::find(1);
$updatedAt = $user->updated_at->toDateTimeString(); // 输出: "2024-05-14 03:16:43"
  1. 在模型中自定义 updated_at 属性的访问器:
class User extends Model
{
    public function getUpdatedAtAttribute($value)
    {
        return date('Y-m-d H:i:s', strtotime($value));
    }
}

$user = User::find(1);
$updatedAt = $user->updated_at; // 输出: "2024-05-14 03:16:43"

第一种方式直接使用 toDateTimeString() 方法,这个方法会将 updated_at 字段转换为 "YYYY-MM-DD HH:mm:ss" 格式的日期时间字符串。

第二种方式是在模型中定义一个访问器 (Accessor) 方法,通过 getUpdatedAtAttribute() 方法来自定义输出格式。在这个例子中,我们使用 date('Y-m-d H:i:s', strtotime($value)) 将原始的 updated_at 值转换为 "YYYY-MM-DD HH:mm:ss" 格式的日期时间字符串。

无论使用哪种方式,最终输出的 updated_at 字段都会是完整的日期时间格式。如果您还有其他问题,欢迎继续提问。

posted @ 2024-05-14 14:27  Laravel自学开发  阅读(13)  评论(0编辑  收藏  举报