删除0,如果返回0年或0个月日期格式(Remove 0, if return 0 year or 0

2019-09-29 08:21发布

$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

Answer 1:

由于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);


Answer 2:

有一个更好的解决方案,而不是使用diffForHumans()和删除agostr_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(); 


文章来源: Remove 0, if return 0 year or 0 month DateFormat