datetime diff不起作用

时间:2010-06-12 14:32:54

标签: php

这是我的代码

    function check($dt) {
    $date = date("Y-m-d");
    $start = new DateTime($date);
    $end   = new DateTime($dt);
    $diff  = $start->diff( $end );

    return $diff->format( '%d days' );
    }

print check('2009-12-14');

打印29天

我哪里错了?

1 个答案:

答案 0 :(得分:7)

manual

中对此进行了解释
<?php

$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

你想:

function check($dt) {
    $date = date("Y-m-d");
    $start = new DateTime($date);
    $end   = new DateTime($dt);
    $diff  = $start->diff( $end );

    return $diff->format( '%a days' );
}

print check('2009-12-14');

给出180 days