PHP date_sub. can't substract today and date

不想你离开。 提交于 2019-12-20 07:28:43

问题


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 ?

<?php

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

echo date_diff($date,$today);

?>

回答1:


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:
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



来源:https://stackoverflow.com/questions/39454071/php-date-sub-cant-substract-today-and-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!