PHP, MySQL: Calculate Number of Days between 2 Dates or Number of Hours, Minutes and Seconds

by Yang Yang on June 13, 2009

Share This Article:
Subscribe to Kavoir: blog feed

This is a rather common task in both PHP and MySQL, that is, to calculate and get the days distance (number of days) between 2 given dates.

In PHP, to get the number of days between now and a future date / a past date:

$days = abs(strtotime("2011-11-20") - strtotime(date("Y-m-d"))) / (60 * 60 * 24);

To get the number of days between 2 given dates, just modify the latter strtotime() parameter:

$days = abs(strtotime("2011-11-20") - strtotime("2005-5-4")) / (60 * 60 * 24);

To get the number of hours between 2 dates:

$days = abs(strtotime("2011-11-20") - strtotime("2005-5-4")) / (60 * 60);

Similarly, to get the number of minutes:

$days = abs(strtotime("2011-11-20") - strtotime("2005-5-4")) / 60;

Number of seconds:

$days = abs(strtotime("2011-11-20") - strtotime("2005-5-4"));

In MySQL, to get the number of days between 2 given dates, use the function TO_DAYS():

SELECT TO_DAYS('2009-07-04') - TO_DAYS('2009-06-18');

Which would return:

16

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 1 comment… read it below or add one }

Pasquale Corzine March 19, 2010 at 3:27 am

Great article I’ve learning php. Your tuts help a lot

Reply

Leave a Comment

Previous post:

Next post: