tags:

views:

145

answers:

3

If I have a couple of strings $startDate and $endDate which are set to (for instance) "2011/07/01" and "2011/07/17" (meaning 1 July 2011 and 17 July 2011). How would I count the days from start date to end date? In the example given, it would be 17 days.

+1  A: 

PHP has a date_diff() function to do this.

Paul Schreiber
+4  A: 

Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

Or:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

You can then get the interval as a integer by calling $interval->days.

wuputah
That doesn't seem to work with my initial strings of "2011/07/01" and "2011/07/17" ... "Call to undefined function date_diff().." . I'm using PHP 5.2.10
cannyboy
Per the documentation (linked at the top), this is PHP >= 5.3.0. For next time, please include the PHP version in your question.
wuputah
+1  A: 

Here is the raw way to do it

$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);
Axsuul
Will not work correctly when you have local dates that include a dayling savings time switchover, because on those dates you have days with 23 or 25 hours.
Michael Borgwardt
Thanks. Appears to work for me.
cannyboy
Actually, it says 16 days for those dates.. Do I need to make dates ignore daylight saving time..?
cannyboy
It should be 16 days because July 1 and July 17 are 16 days apart whereas July 1 and July 18 are 17 days apart
Axsuul