如何配置Nesbot Carbon的diffForHumans()自定义时间差显示规则?
问题描述
我目前使用Nesbot Carbon的diffForHumans()方法时,它只会显示单部分时间差,示例如下:
echo Carbon::create('1 hour 59 minutes ago')->diffForHumans(); // 1 hour ago echo Carbon::create('1 day 23 hours ago')->diffForHumans(); // 1 day ago echo Carbon::create('1 month 23 days ago')->diffForHumans(); // 1 month ago echo Carbon::create('1 year 10 months ago')->diffForHumans(); // 1 year ago
我希望实现以下规则:
- 时间差不超过25个月时,优先显示月数而非年数(比如显示
23 months ago而非1 year ago) - 更通用的规则:当高一级时间单位(如年)为1或2时,保留低一级单位(如月)显示
- 显示形式要尽可能简洁紧凑
实现方案
方法一:自定义格式化函数
直接通过手动计算时间差的各单位值,结合规则拼接结果,代码示例:
function customDiffForHumans(\Carbon\Carbon $date) { $now = \Carbon\Carbon::now(); $diffInMonths = $date->diffInMonths($now); $diffInYears = $date->diffInYears($now); // 处理年-月规则:25个月内或年数≤2时,显示总月数 if ($diffInMonths <= 25 || $diffInYears <= 2) { return "{$diffInMonths} months ago"; } $diffInDays = $date->diffInDays($now); $diffInMonthsTotal = $date->diffInMonths($now); // 处理月-天规则:60天内(约2个月)或月数≤2时,显示总天数 if ($diffInDays <= 60 || $diffInMonthsTotal <= 2) { return "{$diffInDays} days ago"; } $diffInHours = $date->diffInHours($now); // 处理天-小时规则:48小时内(2天)或天数≤2时,显示总小时数 if ($diffInHours <= 48 || $diffInDays <= 2) { return "{$diffInHours} hours ago"; } // 剩余情况显示分钟数 $diffInMinutes = $date->diffInMinutes($now); return "{$diffInMinutes} minutes ago"; } // 测试用例 echo customDiffForHumans(\Carbon\Carbon::create('23 months ago')); // 输出:23 months ago echo customDiffForHumans(\Carbon\Carbon::create('1 year 10 months ago')); // 输出:22 months ago echo customDiffForHumans(\Carbon\Carbon::create('2 days 23 hours ago')); // 输出:47 hours ago echo customDiffForHumans(\Carbon\Carbon::create('3 years ago')); // 输出:36 months ago
方法二:扩展Carbon类(优雅复用)
通过继承Carbon类添加自定义方法,方便全局调用:
use Carbon\Carbon; class CustomCarbon extends Carbon { public function customDiffForHumans() { $now = static::now(); $diffInMonths = $this->diffInMonths($now); $diffInYears = $this->diffInYears($now); if ($diffInMonths <= 25 || $diffInYears <= 2) { return "{$diffInMonths} months ago"; } $diffInDays = $this->diffInDays($now); $diffInMonthsTotal = $this->diffInMonths($now); if ($diffInDays <= 60 || $diffInMonthsTotal <= 2) { return "{$diffInDays} days ago"; } $diffInHours = $this->diffInHours($now); if ($diffInHours <= 48 || $diffInDays <= 2) { return "{$diffInHours} hours ago"; } $diffInMinutes = $this->diffInMinutes($now); return "{$diffInMinutes} minutes ago"; } } // 使用示例 echo CustomCarbon::create('1 year 10 months ago')->customDiffForHumans(); // 22 months ago echo CustomCarbon::create('2 days 23 hours ago')->customDiffForHumans(); // 47 hours ago
规则适配说明
- 针对年和月:优先用总月数展示,直到时间差超过25个月(即2年1个月),此时才切换为年数相关的展示
- 针对月和天:2个月以内(约60天)的时间差,直接展示总天数,避免显示"1个月XX天"的冗余格式
- 针对天和小时:2天以内的时间差,直接展示总小时数,保持紧凑性
内容的提问来源于stack exchange,提问作者PaulH
相关产品推荐
相关产品推荐

