Possible Duplicates:
Difference between dates How to calculate the date difference between 2 dates using php
So, I have two dates. For instance, 2010-09-24
and 2010-09-25
. I want to check if between those two dates the difference is 1 day.
I don't need to get a valu开发者_Python百科e of 86400
which means one day in seconds.
Don't forget that it can be 28, 28, 29, 30, 31 days in month.
Thanks.
What I have right now, but it doesn't work when there is difference between months:
$strto = strtotime($date);
$d1 = date('d', $strto);
$d2 = date('d', time());
echo $d2- $d1;
You can use strtotime to get the number of seconds in between
echo abs(strtotime('2010-09-24') - strtotime('2010-09-25'));
Don't use the day value - (eg date('d', ...)
) - leave it as an integer (the result of strtotime()
). Then subtract those dates, and then get the floor(difference / 86400)
.
Like so:
$dt = strtotime($date);
echo floor(abs(time() - $dt) / 86400);
You can do this nicely with the DateTime class if you have PHP 5.3:
<?php
$datetime1 = new DateTime('2010-09-25');
$datetime2 = new DateTime('2010-09-26');
$interval = $datetime1->diff($datetime2);
$intervaldays = (int) $interval->format('%R%d'); // %R signs the result +/-
This is probably less efficient than using strtotime methods, but it is very readable.
Why are you using date('d'...
which returns the day of the month?
strtotime
will create a UNIX-timestamp which is exactly what time()
returns, so abs(time() - strtotime($date))
should already do the job. This way you don't have to worry how many days a month has as you're only working with timestamps.
This will get you the number of (complete) days:
floor( abs(time() - strtotime($date)) / 86400 )
精彩评论