How to sum N number of time (HH:MM Format)?
Asked Answered
C

6

13

I am using the following sample code to calculate sum of two different time values. Now I want to get the sum of N number of time values.

// numbers for testing
$o="12:59";
$p="0:58";

// display for testing
echo "$o<br />";
echo "$p<br />";
echo AddPlayTime($o,$p);

// FUNCTION - ADD HOURS and MINUTES
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {
  $old=explode(":",$oldPlayTime);
  $play=explode(":",$PlayTimeToAdd);

  $hours=$old[0]+$play[0];
  $minutes=$old[1]+$play[1];

  if($minutes > 59){
    $minutes=$minutes-60;
    $hours++;
  }

  if($minutes < 10){
    $minutes = "0".$minutes;
  }

  if($minutes == 0){
    $minutes = "00";
  }

  $sum=$hours.":".$minutes;
  return $sum;
}
Contagious answered 27/3, 2014 at 8:16 Comment(4)
instead of checking if minutes are less then 10 you can have a look at number_format functionDomineca
and for N numbers of time you can add all your values to an array then pass it to the function.Domineca
@Domineca Thanks for your response, How to do that with array?Contagious
possible duplicate of PHP Convert from strtotime into timeEury
D
41

this should do what you are looking for:

$times is the array of times and you can add how many time you want

$times = array();

$times[] = "12:59";
$times[] = "0:58";
$times[] = "0:02";

// pass the array to the function
echo AddPlayTime($times);

function AddPlayTime($times) {
    $minutes = 0; //declare minutes either it gives Notice: Undefined variable
    // loop throught all the times
    foreach ($times as $time) {
        list($hour, $minute) = explode(':', $time);
        $minutes += $hour * 60;
        $minutes += $minute;
    }

    $hours = floor($minutes / 60);
    $minutes -= $hours * 60;

    // returns the time already formatted
    return sprintf('%02d:%02d', $hours, $minutes);
}

EDIT

I edited the code with the right names of the variables. It is more correct now.

hope this helps :-)

Domineca answered 27/3, 2014 at 9:6 Comment(2)
@Contagious i edited the code with the right name of variables, i did i mistake in the previous code. Now it's more correct :) and i'm glad that was what you needed!Domineca
getting this notice: Undefined variable: minutesManella
M
7

Here is an function that will sum all your time values in format HH:MM:

function sum_time() {
    $i = 0;
    foreach (func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }
    if ($h = floor($i / 60)) {
        $i %= 60;
    }
    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06

demo

Metameric answered 27/3, 2014 at 9:10 Comment(0)
K
0
function sumarHoras($acumuladoTime, $nuevoTime){

    //Se esperan parametros así:
    //$acumuladoTime="02:45";
    //$nuevoTime="04:36";
    //echo "Hora acumulada: $acumuladoTime"."<br>";
    //echo "Nuevo tiempo acumulado: $nuevoTime"."<br>";

    /*Tiempo acumulado*/
    $myArrayAcumuladoTime=explode(":", $acumuladoTime);

    $hrsAcumuladoTime=$myArrayAcumuladoTime[0];
    $minsAcumuladoTime=$myArrayAcumuladoTime[1];

    /*Nuevo Time*/
    $myArrayNewTime=explode(":", $nuevoTime);

    $hraNewTime=$myArrayNewTime[0];
    $minNewTime=$myArrayNewTime[1];

    /*Calculo*/
    $sumHrs=$hrsAcumuladoTime+$hraNewTime;
    $sumMins=$minsAcumuladoTime+$minNewTime;

    /*Si se pasan los MINUTOS*/
    if($sumMins>59){
      /*Quitamos hora para dejarlo en minutos y se la sumamos a la de horas*/
      $sumMins-=60;
      $sumHrs+=1;
    }

    // echo "Total hrs agregadas: $sumHrs:$sumMins"."<br>";
    return "$sumHrs:$sumMins";
  }
Kaffiyeh answered 5/2, 2017 at 2:25 Comment(0)
T
0

This is the best way:

<?php

    function CalculateTime($times) {
        $i = 0;
        foreach ($times as $time) {
            sscanf($time, '%d:%d', $hour, $min);
            $i += $hour * 60 + $min;
        }

        if($h = floor($i / 60)) {
            $i %= 60;
        }

        return sprintf('%02d:%02d', $h, $i);
    }

    $date[] = '02:32';
    $date[] = '01:29';
    echo CalculateTime($date);

?>
Tuft answered 15/1, 2019 at 14:4 Comment(1)
Can you elaborate a bit on why this is the best way?Ordinary
V
0

Laravel Framework (PHP language)

     $chores = ChoresTime::where('family_id', $family->id)->get();
        $total = [];
        foreach ($chores as $key => $value) {
            $total[] = $value->time;
        }
      $total = CalculateTime($chores);
      return response()->json([
          'status' => 1, 
          'message' => 'Total Time', 
          'data' => [], 
          'total' => $total 
      ], ok());

Answer:

{
    "status": 1,
    "message": "Family Total Chores Time",
    "data": [],
    "total": "14:22"
}
Veal answered 12/2, 2020 at 9:2 Comment(0)
R
0

I have extended the above sum_time function to seconds:

function sum_time()
{
    $hh = 0;
    $mm = 0;
    $ss = 0;
    foreach (func_get_args() as $time)
    {
       sscanf( $time, '%d:%d:%d', $hours, $mins, $secs);
       $hh += $hours;
       $mm += $mins;
       $ss += $secs;
    }

    $mm += floor( $ss / 60 ); $ss = $ss % 60;
    $hh += floor( $mm / 60 ); $mm = $mm % 60;
    return sprintf('%02d:%02d:%02d', $hh, $mm, $ss);
}
Roughage answered 30/12, 2022 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.