简体   繁体   中英

DateTime diff returning wrong value

I would like to return the number of days between NOW and some datetime using DateTime object. My dates are:

$now = "2018-03-08 14:00:00";
$last = "2018-02-06 20:00:00"; 

And I do it like this:

$now = new DateTime();
$last_dt = new DateTime($last);
$difference = $last_dt->diff($now);

$difference->format('%d');

$num_of_days = $difference->d;

For some weird reason, the value of $num_of_days is 1 (instead of like 30)

Anybody knows why please?

Thank you

You need to use DateInterval::$days to get the total in days.

DateInterval::$d is just the number of days but in "grouping form", ie 32 days difference will return 2 for DateInterval::$d and 1 for DateInterval::$m .

$last = "2018-04-10 20:00:00"; 

$now = new DateTime();
$last_dt = new DateTime($last);
$difference = $last_dt->diff($now);

echo "Difference: ".$difference->m." months and ".$difference->d." days, or ".$difference->days." days in total";

Result

Difference: 1 months and 2 days, or 33 days in total

Demo

You can see more in the manual

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