计算时间差并在PHP中对结果求和

时间:2014-08-15 05:05:08

标签: php arrays datetime

我有一个数组包含字符串中的时间数据,如下所示:

$time = [
    "10:05:32",
    "11:03:43",
    "13:43:16",
    "10:17:21"
];

现在我要计算$time[x] - 10:00:00,并总结所有结果:00:05:32 + 01:03:43 + 03:43:16 + 00:17:21(= 5:09:52)

我在php.net上读过一些参考资料,但是一切都是关于日期的,没有简单时间计算的解决方案?

3 个答案:

答案 0 :(得分:2)

我要做的是先将它们转换为时间戳,然后映射差异然后总结它们。像这样:

$diff = '10:00:00';
$time = ["10:05:32", "11:03:43", "13:43:16", "10:17:21"];
$time = array_map(function($t) use ($diff){
    return strtotime($t) - strtotime($diff);
}, $time);

$time = gmdate('H:i:s', array_sum($time));
echo $time; // 05:09:52

答案 1 :(得分:1)

尝试以下工作代码

$time = array("10:05:32", "11:03:43", "13:43:16", "10:17:21");
$seconds=0;
foreach ($time as $value){
    list($h,$m,$s)=split(":",$value);       
    $seconds=$seconds+($s+($h*3600)+($m*60))-36000;
}
$output = gmdate("H:i:s", $seconds);
echo $output;

//输出是05:09:52

答案 2 :(得分:0)

 function dateDifference($startDate, $endDate) 
        { 
            $startDate = strtotime($startDate); 
            $endDate = strtotime($endDate); 
            if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate) 
                return false; 

            $years = date('Y', $endDate) - date('Y', $startDate); 

            $endMonth = date('m', $endDate); 
            $startMonth = date('m', $startDate); 

            // Calculate months 
            $months = $endMonth - $startMonth; 
            if ($months <= 0)  { 
                $months += 12; 
                $years--; 
            } 
            if ($years < 0) 
                return false; 

            // Calculate the days 
                        $offsets = array(); 
                        if ($years > 0) 
                            $offsets[] = $years . (($years == 1) ? ' year' : ' years'); 
                        if ($months > 0) 
                            $offsets[] = $months . (($months == 1) ? ' month' : ' months'); 
                        $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now'; 

                        $days = $endDate - strtotime($offsets, $startDate); 
                        $days = date('z', $days);    

            return array($years, $months, $days); 
        } 

这会接受formats listed on this page中的任何一个,包括小时分秒,这就是你看起来有的......希望有所帮助。