nika nika - 1 month ago 6x
PHP Question

PHP date_sub. can't substract today and date

I am trying to output number of days between today and the date I enter so I have a problem I encounter error: "Warning: date_diff() expects parameter 2 to be DateTimeInterface" So what's the problem ?



echo date_diff($date,$today);



Your problem lies in that when using date_diff you have to make sure that you're comparing objects that are actual date objects. Also the return type for date_diff is a DateInterval object. You're treating it as a string.

$today = new DateTime(); // $today is a DateTime object
$date = new DateTime("2016-09-16"); // $date is also a DateTime object!
$diff =  date_diff($date,$today); // compare two objects of the same type FTW!

echo $diff->days; // $diff is a DateInterval object, so echo it's 'days' property.

// output: 3 (as of this writing)

Further reading: