比如说有这样一个需求:一篇文章的发表时间:
距离现在时间显示格式
小于1小时 xx分钟前
1小时至24小时 xx小时前
1天至10天 xx天前
大于10天 直接显示日期
首先:
在你的app/Providers/AppServiceProvider.php
中boot函数中添加
Carbon::setLocale('zh');
这一行到boot()方法当中,(为了中文化显示)
use Carbon\Carbon
public function boot()
{
//
Carbon::setLocale('zh');
}
然后在controller中添加
public function getCreatedAtAttribute($date) {
if (Carbon::now() > Carbon::parse($date)->addDays(10)) {
return Carbon::parse($date);
}else{
return Carbon::parse($date)->diffForHumans();
}
}
public function index(){
echo $this->getCreatedAtAttribute('2020-10-03 17:15:00');
}
别忘了在Article头部
use Carbon\Carbon
如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术
转载请注明:Laravel 使用 Carbon 人性化显示文章发表时间 出自老鄢博客 | 欢迎分享