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"
CodePudding user response:
<?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.
CodePudding user response:
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