Remove 0, if return 0 year or 0 month DateFormat

2019-08-13 00:22发布

问题:

$createdTime = Carbon::parse($specialist->created_at)
                        ->diff(Carbon::now())
                        ->format('%y yr, %m mo and %d days');

This returns 0 yr, 0 mo and 8 days. I want to return only 8 days.

Or if 1 yr, 0 mo and 8 days, return 1 yr and 8 days

回答1:

Since diff() returns a DateInterval instance you could run conditional checks to get your expected result.

$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);


回答2:

There is a better solution rather than using diffForHumans() and remove ago with str_replace($time->diffForHumans(), ' ago').

I recommand using the CarbonInterval like this :

$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();