PHP: Get the Number of Days between Two Dates Programming 22 AUG 2013

green php elephants - elephpantsA fairly common programming problem that crops up is calculating the number of days between two dates.

Prior to PHP 5.3 and all the goodness it added to the language, one usually set about calculating this simply by converting both dates to timestamps and then subtracting the one from the other, before finally converting the result into days which would of course be your answer.

Note that this was not particularly useful for all the guys out there using daylight savings time, but for guys like us in South Africa then it was perfectly fine!

In practice, this would have looked something like this:

$now = time(); // or your second date
$your_date = strtotime("2013-01-01");
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));

However, if you do have access to PHP 5.3, and really, you should by now, then you’ll be far better off using the functionality that the clever DateTime construct gives us:

$start_timestamp = time(); // or your second date
$end_timestamp = strtotime("2013-01-01");
$datetime1 = new DateTime(date('Y-m-d', $start_timestamp));
$datetime2 = new DateTime(date('Y-m-d', $end_timestamp));
$interval = $datetime1->diff($datetime2, true);
$days = intval($interval->format('%a'), 10); //or echo $interval->format('%R%a')

Nifty.

Bonus: And say that we wanted to be sure we have a full set of say 7 day periods for a trend graph, then we could use the above in something like this:

$datetime1 = new DateTime(date('Y-m-d', $start_timestamp));
$datetime2 = new DateTime(date('Y-m-d', $end_timestamp));
$interval = $datetime1->diff($datetime2, true);
$days = intval($interval->format('%a'), 10);
$extra = $days % 7;
if ($extra != 0) {
    $extra = 6 - $extra;
}
if ($extra != 0) {
    $start_timestamp = strtotime('-' . $extra . ' days', $start_timestamp);
}

That last one is more of a note to myself than anything else to be honest. Anyway, as per usual, play around with it on the useful PHP Code Pad.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.