0

我试图得到这样的两个日期之间的区别

[
   '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);
4

1 回答 1

0

You could use the diffAsCarbonInterval()

$p = $date2->diffAsCarbonInterval($date1);

Then you can access the above values with:

$p->years //year
$p->months //month
$p->weeks //week
$p->daysExcludeWeeks //day
$p->hours //hour
$p->minutes //minute
$p->seconds //second

Or to take it one step further you could create a macro. One way to do this would be to add the following to the register method of your app service provider:

\Carbon\Carbon::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,
    ];
});

Then you can call:

$p = $date2->diffAsArray($date1);

Obviously, feel free to change the method name of the macro to something else if you want to.

于 2018-08-26T08:37:57.570 回答