减去日期以获得天数 [英] Subtract dates to get the number of days
问题描述
我正在尝试编写一个php代码,它将能够减去两个日期并获得两个日期之间的天数。我想出的代码如下
I am trying to write a php code which will be able to subtract two dates and get the number of days between the two dates. The code I came up with is given below
<?php
$c_date = date("Y-m-d");
//Subtracting two dates.
$date1 = new DateTime($d_date); //$d_date gets its value from database which i havent shown here
$date2 = new DateTime($c_date);
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
?>
现在上面的代码有效,但是我无法使用它来满足我的需要。我需要能够确定交货日期($ d_date)是否在当前日期之后的5天内,如果是这种情况,则返回值1。
Now the above code works but I am not able to use it to suit my needs. I need to be able to find out if the delivery date ($d_date) is within 5 days from the current date and return value 1 if that is that case.
因此,如果 $ c_date = 2013-09-24
和 $ d_date = 2013-09-30
然后我将返回1。
但是麻烦的是,当说交货日期是 2013-09-19时交货日期已经很久了,我应该返回0,但是用当前代码,天的差仍然是5,所以我将返回1,这是错误的。
So if $c_date = "2013-09-24"
and $d_date = "2013-09-30"
then I will be returning 1.
But the trouble is when say the delivery date is "2013-09-19" the delivery date has long past and I should be returning 0, but with the current code the difference in day would still be 5 and so i will be returning 1 which is wrong.
对如何克服这个问题有任何想法吗?
Have any ideas as to how to overcome this?
推荐答案
好的,这就是Maximus2012所建议的必需代码,首先使用if语句比较日期。所以这是代码
Ok so here is the required code, as Maximus2012 suggested, using a if statement to compare the dates first did the work. So here is the code
$date1 = new DateTime($ddate[$counter]);
$date2 = new DateTime($c_date);
if($date2>$date1)
{
$stat = 0;
}
$interval = $date1->diff($date2);
$d_diff = $interval->d;
if($d_diff>5)
{
$stat = 0;
}
这篇关于减去日期以获得天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!