Difference between dates with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles