skip to Main Content

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

I tried this calculating time but it is not working.

3

Answers


  1. 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 CarbonCarbon;
    
    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');
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. Summing times can be done using Carbon like so (less is more):

    use CarbonCarbon;
    $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 CarbonCarbonInterface;
    $str = $time->diffForHumans(Carbon::createFromTimestamp(0), CarbonInterface::DIFF_ABSOLUTE, false, 2);
    // "1 hour 55 seconds"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search