如何在循环php中添加日期时间之间的差异?

时间:2017-09-06 20:16:06

标签: php datetime

我想获得所有创建时间和更改时间之间的平均值,所以我必须在每一行得到差异并添加它,我尝试了下面的代码,但它没有工作,我没有'我知道为什么我单独尝试每个陈述并且运作良好

while($row = $result->fetch_assoc()) {
    $changedon = new DateTime($row['changedon']);
    $createdtime = new DateTime($row['createdtime']);

    if ($i == 0) {
        $total_time = $createdtime->diff($changedon);
        $i++;
    } else {
        $total_time->add($createdtime->diff($changedon));
    }
}

echo $total_time->format('%y years %m months %a days %h hours %i minutes %s seconds');

2 个答案:

答案 0 :(得分:0)

function addtime($time1,$time2)
{
$x = new DateTime($time1);
$y = new DateTime($time2);

$interval1 = $x->diff(new DateTime('00:00:00')) ;
$interval2 = $y->diff(new DateTime('00:00:00')) ;

$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
return $total;
}

答案 1 :(得分:0)

DateInterval不适合计算平均值。你必须自己做一些计算。这可能是一个起点:

$createdSeconds = 0;
$changedSeconds = 0;
$items = 0;
while($row = $result->fetch_assoc()) {
    $changedon = new DateTime($row['changedon']);
    $createdtime = new DateTime($row['createdtime']);
    $createdSeconds += $createdtime->getTimestamp();
    $changedSeconds += $changedon->getTimestamp();
    $items++;
}
printf(
    'Average time between create and change is %d seconds',
    ($changedSeconds - $createdSeconds) / $items
);