Carbon: split datetime diff in hours format (by seconds)

Viewed 223

I'm looking for a way to split the difference and know how much minutes of the hour is consumed, for example:

Date 1: 2021/06/30 10:20PM
Date 2: 2021/06/30 11:20PM

Expected result:
10 PM: 40min
11 PM: 20min

Another example:

Date 1: 2021/06/30 9:54AM
Date 2: 2021/06/30 1:35PM

Expected result:
9AM: 6min
10AM: 60min
11AM: 60min
12PM: 60min
1 PM: 35min

is there a way for caborn to output in this format? the only thing I've found is the difference in hours

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');
$start->diff($end)->format('%H:%I:%S');
outputs = 02:00:06
2 Answers

You can use this....Tested with all your examples

    $d1 = $temp = new Carbon('2021/06/30 10:20PM');
    $d2 = new Carbon('2021/06/30 11:20PM');

    $results = [];
    while ($temp->lt($d2)) {
        $m = 60-$temp->minute;
        if ((clone $temp)->addMinutes($m)->gt($d2)) {
            $m = $d2->minute;
        }
        $results[] = sprintf('%s: %smin', $temp->format('h a'), $m);
        $temp->addMinutes($m);
    }
echo $start->diffAsCarbonInterval($end)->totalMinutes;
Related