Home > Software engineering >  I want to calculate this time Laravel
I want to calculate this time Laravel

Time:01-18

$array = [ '00:09:45', '00:50:05', '00:01:05', ]

I tried this calculating time but it is not working.

CodePudding user response:

I understand that by calculate he meant addition. (Nuances related to translation). Below is an example function in Laravel that adds these times from an array. You should use Carbon for this purpose.

use Carbon\Carbon;

function addTimes($times) {
    $totalTime = Carbon::createFromTime(0, 0, 0);
    foreach ($times as $time) {
        $time = Carbon::createFromFormat('H:i:s', $time);
        $totalTime->addSeconds($time->secondsSinceMidnight());
    }
    return $totalTime;
}

$times = [ '00:09:45', '00:50:05', '00:01:05', ];
$totalTime = addTimes($times);

echo $totalTime->format('H:i:s');

CodePudding user response:

I believe you want sum the durations of time. We can transform it in a collection and reduce it by adding the times.

use Carbon/Carbon;

$array = collect(['12:09:45', '11:50:05', '07:01:05']);
$total = $array->reduce(function ($time, $timeNext){
    $carbonTimeNext = new Carbon($timeNext);
    $time->addHours($carbonTimeNext->format('H'))
        ->addMinutes($carbonTimeNext->format('i'))
        ->addSeconds($carbonTimeNext->format('s'));
    return $time;
}, new Carbon('00:00:00'));

echo $total->shortAbsoluteDiffForHumans(new Carbon('00:00:00'), 6);

//output: 1d 7h 55s

CodePudding user response:

Summing times can be done using Carbon like so (less is more):

use Carbon\Carbon;
$times = ['00:09:45', '00:50:05', '00:01:05'];

$time = Carbon::createFromTimestamp(array_reduce($times, function($sum, $item) {
    return $sum   Carbon::createFromTimestamp(0)->setTimeFromTimeString($item)->timestamp;
}));

Note: the resulting $time variable is a Carbon date from unix time = 0 with the times added from your array.

The sum of seconds from your array can thus be retrieved using the timestamp property, which is the amount of seconds since the start of the unix epoch:

$sumSeconds = $time->timestamp;
// 3655

Displaying it as a string goes as follows:

use Carbon\CarbonInterface;
$str = $time->diffForHumans(Carbon::createFromTimestamp(0), CarbonInterface::DIFF_ABSOLUTE, false, 2);
// "1 hour 55 seconds"
  • Related