获取两个日期PHP之间的平均间隔

时间:2014-07-15 13:36:31

标签: php date-manipulation

所以我有以下数组($lifeSpanArray),我想计算两个日期之间的平均间隔。

到目前为止我所拥有的,但我认为我认为它有点错误:

<?php
    foreach ($lifeSpanArray as $key) {

        $newTimeAdd = new DateTime($key["timeAdded"]);
        $newTimeRead = new DateTime($key["timeRead"]);

        $interval = $newTimeAdd->diff($newTimeRead);
        var_dump($interval);
    }
?>

哪个输出:

Array
(
    [0] => Array
    (
        [timeAdded] => 07/15/2014
        [timeRead] => 07/15/2014
    )
    [1] => Array
    (
        [timeAdded] => 07/14/2014
        [timeRead] => 07/14/2014
    )
    [2] => Array
    (
        [timeAdded] => 07/13/2014
        [timeRead] => 07/15/2014
    )

    [3] => Array
    (
        [timeAdded] => 07/13/2014
        [timeRead] => 07/13/2014
    )

    [4] => Array
    (
        [timeAdded] => 07/12/2014
        [timeRead] => 07/12/2014
    )

    [5] => Array
    (
        [timeAdded] => 07/12/2014
        [timeRead] => 07/12/2014
    )

    [6] => Array
    (
        [timeAdded] => 07/12/2014
        [timeRead] => 07/12/2014
    )

    [7] => Array
    (
        [timeAdded] => 07/12/2014
        [timeRead] => 07/12/2014
    )

    [8] => Array
    (
        [timeAdded] => 07/12/2014
        [timeRead] => 07/12/2014
    )

    [9] => Array
    (
        [timeAdded] => 07/11/2014
        [timeRead] => 07/11/2014
    )

    [10] => Array
    (
        [timeAdded] => 07/11/2014
        [timeRead] => 07/11/2014
    )

    [11] => Array
    (
        [timeAdded] => 07/10/2014
        [timeRead] => 07/11/2014
    )

    [12] => Array
    (
        [timeAdded] => 07/10/2014
        [timeRead] => 07/10/2014
    )
)

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

 <?php
        $intervals = array();
        foreach ($lifeSpanArray as $key) {

            $newTimeAdd = new DateTime($key["timeAdded"]);
            $newTimeRead = new DateTime($key["timeRead"]);
            $interval = $newTimeAdd->diff($newTimeRead);
            $intervals[] = $interval->days;//get days
        }
        if(!empty($intervals))
        {
            $average = average($intervals);
        }


    function average($arr)
    {
       return array_sum($arr)/count($arr);
    }

?>

答案 1 :(得分:0)

您的解决方案是正确的,但不要伪造从diff调用返回的对象上的format()方法。

来自PHP.net的示例:

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>