我试图像这样了解两个日期之间的差异
[
'years' : 4, // 0 if the difference is not above a year
'months': 4, // 0 if the difference is not of above a month
'weeks': 4, // 0 if the difference is not of above a week
'days': 4, // 0 if the difference is not of above a day
'hours' : 4 // 0 if the difference is not of above a hour
'minutes': 54 // 0 if the difference is not of above a minute
'seconds': 5 // 0 if the difference is not of above a second
]
是否有任何实用程序函数可以在 laravel PHP 中为我提供类似上面的输出
这是我目前的代码
$date1 = new Carbon('2018-08-18 11:09:12');
$date2 = new Carbon('2018-04-02 08:15:03');
// dd($date1->diffForHumans($date2, false, false, 6));
$p = $date2->diffForHumans($date1, false, false, 6);
你可以使用 diffAsCarbonInterval((
$p = $date2->diffAsCarbonInterval($date1);
然后,您可以使用以下命令访问上述值:
$p->years //year
$p->months //month
$p->weeks //week
$p->daysExcludeWeeks //day
$p->hours //hour
$p->minutes //minute
$p->seconds //second
或者更进一步,您可以创建一个宏。执行此操作的一种方法是将以下内容添加到应用服务提供商的注册方法:
CarbonCarbon::macro('diffAsArray', function ($date = null, $absolute = true) {
$interval = $this->diffAsCarbonInterval($date, $absolute);
return [
'year' => $interval->years,
'month' => $interval->months,
'week' => $interval->weeks,
'day' => $interval->daysExcludeWeeks,
'hour' => $interval->hours,
'minute' => $interval->minutes,
'second' => $interval->seconds,
];
});
然后你可以打电话:
$p = $date2->diffAsArray($date1);
显然,如果需要,可以随意将宏的方法名称更改为其他名称。