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:

pre-5.3

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

echo $interval->format('%a');

5.3+

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. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles