简体   繁体   中英

datetime diff doesn't work

here is my code

    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');

that prints 29 days

where am i wrong ?

It's explained in the 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');

?>

You want:

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');

gives 180 days .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM