$createdTime = Carbon::parse($specialist->created_at)
->diff(Carbon::now())
->format('%y yr, %m mo and %d days');
这将返回0 yr, 0 mo and 8 days
。 我只想返回8 days
。
或者,如果1 yr, 0 mo and 8 days
,返回1 yr and 8 days
由于diff()
返回一个DateInterval
例如,你可以运行条件检查,让您预期的结果。
$createdTime = Carbon::parse($specialist->created_at)
->diff(Carbon::now());
$final_string = '';
$year = '';
$month = '';
$days = '';
if ($createdTime->y) {
$year = $createdTime->y . ' yr';
}
if ($createdTime->m) {
$month = ' '. $createdTime->m . ' mo';
}
if ($createdTime->d) {
$days = ' ' . $createdTime->d . ' days';
}
$final_string = trim($year . $month . $days);
有一个更好的解决方案,而不是使用diffForHumans()
和删除ago
与str_replace($time->diffForHumans(), ' ago')
我使用推荐的CarbonInterval是这样的:
$now = Carbon::now();
$years = $specialist->created_at->diffInYears($now);
$months = $specialist->created_at->diffInDays($now->subYears($years));
$days = $specialist->created_at->diffInDays($now->subMonths($years));
// $hours = $specialist->created_at->diffInHours($now->subDays($days));
// $minutes = $specialist->created_at->diffInMinutes($with_duration->subHours($hours));
// $seconds = $specialist->created_at->diffInSeconds($with_duration->subMinutes($minutes));
return CarbonInterval::years($years)->months($months)->days($days)->forHumans();
//return CarbonInterval::years($years)->months($months)->days($days)->hours($hours)->minutes($minutes)->seconds($seconds)->forHumans();