PHPdate_sub。不能减去今天和日期

PHP date_sub. can't substract today and date

我试图输出今天和我输入的日期之间的天数,所以我遇到了一个问题,我遇到了错误:"Warning: date_diff() expects parameter 2 to be DateTimeInterface" 那么问题是什么?

<?php

$today=date("y-m-d");
$date=date_create("2016-09-16");

echo date_diff($date,$today);

?>

您的问题在于,在使用 date_diff 时,您必须确保比较的对象是实际日期对象。 date_diff 的 return 类型也是 DateInterval 对象。您将其视为字符串。

$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)

进一步阅读:
http://php.net/manual/en/class.dateinterval.php
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/function.date-diff.php