Skip to main content

With PHP 5 they introduced the DateTime class.  Prior to that everyone used strtotime, date, etc…commands to achieve the same results.  I was a late adopter and continued to use the old commands.  Recently I decided it’s been long enough and it’s time to take a look at this new class and apply it.

This example is a simple how to on showing the difference between two dates in day format.

So my start date here is 2016-05-04 10:20:42 as it’s stored in the MySQL timestamp field of my database.  The end date is another date in the same format of YYYY-MM-DD HH:MM:SS.

My first attempt mixed some of the old and new functions together to get my result.

$reg_temp = strtotime('2016-05-04 10:20:42');
$registration_date = date("Y-m-d", $reg_temp);
$exp_temp = strtotime('2017-05-04 10:20:42');
$expiration_date = date("Y-m-d", $exp_temp);

$registration_date = date_create($registration_date);
$expiration_date = date_create($expiration_date);

$diff=date_diff($registration_date,$expiration_date);
echo $diff->format("%R%a days");

While it did get me the end result, that’s a lot of code to accomplish what I want.  And I also want to force myself to only use the new DateTime class.  After a few more iterations I came up with this that does the same job in 4 nice and clean lines of code:

$registration_date = date_create('2016-05-04 10:20:42'); //Replace static date with your database field
$expiration_date = date_create('2017-05-04 10:20:42'); //Replace static date with your database field

$diff=date_diff($registration_date,$expiration_date);
echo $diff->format("%R%a days");

Much better.  You can see the demo output here.

Leave a Reply