tags:

views:

86

answers:

4

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 value 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;
+1  A: 

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 )
Select0r
No it won't do the job, because `$date` and `time()` can have only, for example, 5 seconds.
hey
Then I didn't get your question as well as what you mean by "can have only 5 seconds" ... how can `time()` "have 5 seconds" ??? If the return value is bothering you, use `floor(value/86400)` to get the number of days instead of seconds.
Select0r
I think I have misunderstood the strtotime function.
hey
+1  A: 

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);
mway
+1  A: 

You can use strtotime to get the number of seconds in between

echo abs(strtotime('2010-09-24') - strtotime('2010-09-25'));
Galen
Just watch out in case the date range encompasses the change for daylight savings, because then your seconds result won't be a whole number of days
Mark Baker
@Mark Baker : What do you mean?
hey
echo abs(strtotime('2010-09-24') - strtotime('2010-09-25')); would normally return 86400; but if the daylight savings began or ended on '2010-09-24', then you'd get a return value of 82800 or 90000 depending on whether the clocks were going forward or back (assumption of 1hr and a timezone that implements daylight saving). To avoid problems, you can set date_default_timezone_set('GMT'); before doing the calculation, and set it back again afterwards, because GMT is constant through the year (no daylight saving).
Mark Baker
@Mark Baker: Thank you. I'll surely do.
hey
+1  A: 

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.

lonesomeday