Laravel 自带时间处理函数 - Carbon 的 diffForHumans 方法

xiaoxiao2021-02-28  50

Carbon 是继承自 PHP DateTime 类 的子类,但比后者提供了更加丰富、更加语义化的 API。其中一个比较实用的 API 就是 diffForHumans 方法,几乎每个用 Laravel 构建的项目中都有用到它。

比如,一个博客系统里的文章发布时间,显示格式可能就像下面这样:

**距离现在时间** **显示格式** < 1小时 xx分钟前 1小时 - 24小时 xx小时前 1天 - 15天 xx天前 > 15天 直接显示日期

第一步: 本地化 Carbon。在 AppServiceProvider 的 boot 方法中添加 Carbon::setLocale(‘zh’)。

Carbon::setLocale('zh');

第二步: 在 Model 中设定要人性化显示的字段。以 Article Model 的 created_at 字段为例。

public function getCreatedAtAttribute($value){ return Carbon::createFromFormat('Y-m-d H:i:s', $value)->diffForHumans(); }

下面就可以直接使用了。

$article->created_at;

作者:不动峰 博客园:http://www.cnblogs.com/mylly/ 版权所有,欢迎保留原文链接进行转载:)

转载请注明原文地址: https://www.6miu.com/read-2632146.html

最新回复(0)