How to Sum N values in time format (hh:mm:ss)?

2.7k views Asked by At

I used date_parse function and added some time values.

print_r(date_parse("23:00:00"));
$parsed = date_parse($totdh);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
$TotDownMinutes = $seconds / 60;

i had problem when the sum exceeds 24 hours. it just omits 2 if it is 25 hours and just takes 5 as hours.

Array ( [year] => [month] => [day] => [hour] => 23 [minute] => 0 [second] => 
0 [fraction] => 0 [warning_count] => 0 [warnings] => Array ( ) [error_count]
=> 0 [errors] => Array ( ) [is_localtime] => ) 

print_r(date_parse("26:00:00"));
Array ( [year] => [month] => [day] => [hour] => 6 [minute] => 0 [second] => 
0 [fraction] => 0 [warning_count] => 0 [warnings] => Array ( ) [error_count]
=> 1 [errors] => Array ( [0] => Unexpected character ) [is_localtime] => ) 

Tell me how can i add time values (like 12:30:00 + 14:00:00 + 02:00:00 = 28:30:00).

2

There are 2 answers

0
Richard Cross On

Alternatively:

$times = [ '10:30:22', '23:16:49' ];
$sum = [ 'h'=>0,'m'=>0,'s'=>0 ];

foreach( $times as $time ) {
    list($h,$m,$s) = explode(':',$time);
    $sum['h'] += $h;
    $sum['m'] += $m;
    $sum['s'] += $s;
}

$sum['m'] += floor($sum['s']/60);
$sum['h'] += floor($sum['m']/60);
$sum['s'] = $sum['s']%60;
$sum['m'] = $sum['m']%60;

echo implode(':',$sum);
0
Anders On

This is perhaps not a very elegant solution, but at least I think it should solve your problem.

$total = 0;
$times = array('12:30:00', '14:00:00', '02:00:00');

foreach($times as $t) {
    $total += toSeconds($t);
}

echo toTime($total);

function toSeconds($time) {
   $parts = explode(':', $time);
   return 3600*$parts[0] + 60*$parts[1] + $parts[2];
}

function toTime($seconds) {
    $hours = floor($seconds/3600);
    $seconds -= $hours * 3600;
    $minutes = floor($seconds/60);
    $seconds -= $minutes * 60;
    return $hours . ':' . $minutes . ':' . $seconds;
}

Please note that toSeconds do not check that the string is properly formatted.