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.





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: