0

我想获得平均小时数,但我遇到了问题,因为如果我使用 DateTime.add() 对象在超过 24 小时时添加时间,它会将时间转换为“日”。基本上我只想在“小时”内获得这些时间的平均值。请帮忙。

$time = array();
$time[] = '00:00:58';
$time[] = '00:45:08';
$time[] = '00:00:49';
$time[] = '00:11:26';
$time[] = '02:34:39';
$time[] = '02:18:24';
$time[] = '02:24:11';
$time[] = '01:23:19';
$time[] = '00:27:30';
$time[] = '02:14:50';
$time[] = '00:48:47';
$time[] = '02:19:52';
$time[] = '02:04:29';
$time[] = '01:08:46';
$time[] = '00:06:57';
$time[] = '00:35:31';
$time[] = '02:16:59';
$time[] = '02:23:33';
$time[] = '02:36:30';
$time[] = '02:11:47';
$time[] = '02:40:44';
$time[] = '02:03:42';
$time[] = '01:45:50';
4

3 回答 3

1

尝试这个,

$total_time=0;

foreach($time as $t){
     $total_time+=strtotime($t)-1373241600;
}

所以 $total_time 将是一个整数,您可以将其除以 3600 和 count($time) 以获得平均小时数:)

$average_time = ($total_time/count($time))/3600;
于 2013-07-08T19:07:10.237 回答
0

如果您不想依赖时区设置,减去当天的时间戳或对 strtotime 的迟缓感到恼火,请改用简单的数学:

$timestamps = array_map(function($item){
    list($h, $m, $s) = explode(':', $item);
    return intval($h) * 3600 + intval($m) * 60 + intval($s);
}, $time);
$avg = ceil(array_sum($timestamps)/count($timestamps));
echo gmdate('H:i:s', $avg);
于 2013-07-08T19:28:02.090 回答
0

试试这个(注意闭包在 5.3+ 中可用):

$timestamps = array_map(function($a){return strtotime($a);}, $time);
$avg = (array_sum($timestamps)/count($timestamps))/3600;
于 2013-07-08T19:10:55.073 回答