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.
+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
2010-09-06 19:31:34
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
2010-09-06 21:40:21
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
2010-09-06 23:13:02
+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
2010-09-06 19:46:38
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
2010-09-06 19:53:52
Actually, it says 16 days for those dates.. Do I need to make dates ignore daylight saving time..?
cannyboy
2010-09-06 22:43:20
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
2010-09-06 23:09:28