PHP date_sub。不能减去今天和日期 [英] PHP date_sub. can't substract today and date

查看:91
本文介绍了PHP date_sub。不能减去今天和日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输出从今天到输入的日期之间的天数,因此我遇到一个错误,我遇到一个错误:警告:date_diff()期望参数2为DateTimeInterface那么问题是什么?

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

?>

推荐答案

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

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)

进一步阅读:

http:// php。 net / manual / en / class.dateinterval.php

http://php.net/manual/zh/class.datetime.php

http://php.net/manual/en/function.date-diff.php

这篇关于PHP date_sub。不能减去今天和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆