0

How can i sum times into array using Carbon?

<?php
namespace App\Models;
use Carbon\Carbon;
class Appointment extends BaseModel 
{
  public static function total_time()
  {
    $appointments = Appointment::get();
    $sumtimes = [];
    foreach($appointments as $a){
        $dti = Carbon::parse($a->dateinitial);
        $dtf = Carbon::parse($a->datefinal);
        $time = $dti->diff($dtf)->format('%H:%I:%S');
        $sumtimes[] = $time;
    }
    $sumtimes= sum($sumtimes);
    return $sumtimes;

}

inside sum_times, there is a list of times that need to be summed like:

$sum_times[0] = "00:01:18"
$sum_times[1] = "00:03:11"
$sum_times[2] = "01:01:18"
$sum_times[3] = "00:01:28"

I need it to return "01:07:15"

BatimaReal
  • 11
  • 3
  • You'll need to use a raw number in the array instead of storing it as a string. I'm not sure if you need to use math or if there's an easy way to get just the total number of seconds. – aynber Mar 03 '22 at 18:36
  • You can also get [the timestamps and then subtract them](https://stackoverflow.com/questions/3176609/calculate-total-seconds-in-php-dateinterval) and average those instead. – aynber Mar 03 '22 at 18:40

2 Answers2

1
<?php

public static function total_time(): string
{
    $seconds = 0;

    foreach(Appointment::get() as $appointment){
        $dateinitial = Carbon::parse($appointment->dateinitial);
        $datefinal = Carbon::parse($appointment->datefinal);
        $seconds += $datefinal->diffInSeconds($dateinitial);
    }

    return gmdate('H:i:s', $seconds);
}

Also you must set for your fields (dateinitial, datefinal) cast datetime for automated parsing to Carbon type. Docs for date casts.

rollsover
  • 68
  • 4
  • Good idea with a small caveat. When using gmdate, the number of hours must remain under 24. – jspit Mar 04 '22 at 15:36
  • Oh, sorry, yap: ```php return floor($seconds / 3600) . gmdate(":i:s", $seconds); ``` Example: ```php $seconds = 5 * (60 * 60) + 5 * (60) + 5; echo floor($seconds / 3600) . gmdate(":i:s", $seconds); // Result: 5:05:05 ``` – rollsover Mar 05 '22 at 05:37
0

Each result of diff can be continuously added to a datum. At the end of the loop we get the sum as the difference from the base date to the date. Carbon is an extension of DateTime. I show the sample code with the base class so that it is reproducible for everyone.

$data = [
  ['from' => '2022-03-01 16:00', 'to' => '2022-03-02 12:00'],  //20:00:00
  ['from' => '2022-03-02 12:30', 'to' => '2022-03-02 22:02'],  //09:32:00
];  //total 29:32:00

$basis = '2000-01-01';
$dateBase = date_create('2000-01-01');
$date = clone $dateBase;

foreach($data as $dates){
  $dateFrom = date_create($dates['from']);
  $dateTo = date_create($dates['to']);
  $diff = $dateFrom->diff($dateTo);
  $date->add($diff);
}
$totalDiff = $dateBase->diff($date);
$hours = $totalDiff->d *24 + $totalDiff->h;  //days * 24 + hours

echo 'Sum: '.$hours.$totalDiff->format(':%I:%S');
//Sum: 29:32:00

Try self on 3v4l.org

jspit
  • 7,276
  • 1
  • 9
  • 17