Remove 0, if return 0 year or 0 month DateFormat

非 Y 不嫁゛ 提交于 2019-12-24 09:51:07

问题


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


来源:https://stackoverflow.com/questions/47657517/remove-0-if-return-0-year-or-0-month-dateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!