如何以时间格式汇总N值(hh:mm:ss)?

时间:2015-06-23 13:40:28

标签: php time date-parsing datetime-parsing

我使用了date_parse函数并添加了一些时间值。

print_r(date_parse("23:00:00"));
$parsed = date_parse($totdh);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
$TotDownMinutes = $seconds / 60;
当总和超过24小时时,我遇到了问题。它只是省略了2如果是25小时,只需要5小时。

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] => ) 

告诉我如何添加时间值(如12:30:00 + 14:00:00 + 02:00:00 = 28:30:00)。

2 个答案:

答案 0 :(得分:0)

这可能不是一个非常优雅的解决方案,但至少我认为它应该可以解决你的问题。

$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;
}

请注意toSeconds不检查字符串是否格式正确。

答案 1 :(得分:0)

可替换地:

$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);