简体   繁体   中英

PhP month difference between dates in different years

I have this piece of code which is returning a weird result:

        $d1 = new DateTime('2018-12-01');
        $d2 = new DateTime('2009-02-03');
        $interval = $d2->diff($d1);
        echo $interval->format('%m months');
        die();

It's returning 9 months, which is wrong. The question is mad simple but I couldn't find an answer yet: What am I doing wrong?

You can use Carbon library it works and return 2 month

$d1 = new \Carbon\Carbon('2018-12-01');
$d2 = new \Carbon\Carbon('2019-02-03');
echo $d2->diffInMonths($d1);
die();

https://carbon.nesbot.com/docs/

it works for me!

$datetime1 = date_create('2018-12-01');

$datetime2 = date_create('2009-02-03');

$interval = date_diff($datetime1, $datetime2);

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