柔晶美网络工作室

柔晶美网络工作室,倾心于web技术的博客站点

关注我 微信公众号

您现在的位置是: 首页 > 博客日记

Carbon 的 diffForHumans 方法,laravel的人性化日期

2019-10-06 admin laravel  1709

在博客等文章类程序中,我们需要将发布于7天内的时间,展示为几天前发布,而不是具体的日期,而超过7天的,则显示具体日期,这就需要使用Carbon 的 diffForHumans 方法来实现:

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

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

use Carbon\Carbon;
public function boot() {
    Carbon::setLocale('zh');
}

繁体中文的设置是 Carbon::setLocale('zh-TW'),语言配置文件可在 vendor/nesbot/carbon/src/Carbon/Lang 文件夹下找到。

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

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class BlogModel extends Model
{
    protected $table = 'blog';
protected $fillable = [
        'title', 'tag', 'content','pinglun','views',
    ];
    //人性化日期
public function getCreatedAtAttribute($date) {
if (Carbon::now() > Carbon::parse($date)->addDays(7)) {
//return Carbon::parse($date);
return $date;//大于7天的时间直接返回具体日期
}
return Carbon::parse($date)->diffForHumans();
}
}

显示效果:


文章评论


需要 登录 才能发表评论
热门评论
0条评论

暂时没有评论!