Difference between dates with PHP

Prior to PHP 5.3 the act of calculating the difference between two dates was a
bit more manual than it is now. By manual, I mean there wasn’t a function that
existed to aid in the process if by nothing else, the documentation itself.

Let’s take a look at how you can caculate the difference (in number of days)
between two dates in PHP 5.3+ as well as pre-5.3:


$date1    = new DateTime('2014-11-09'
$date2    = new DateTime('2014-11-11'
$interval = $date1->diff($date2

echo $interval->format('%a'


echo (strtotime('2014-11-11') - strtotime('2014-11-09')) / 86400

Okay, so it looks like the pre-5.3 is significantly shorter. If I had to guess,
it’s also a ton faster because it relies on less overhead instantiating classes
as well as less calls to functions / methods.

The moral of the story? From time to time, the old way of thinking can be just
as good, if not better than the newer alternatives. That doesn’t mean you should
be close minded though, it’s always worth it to explore all of the options.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.