Categories
PHP Tips & Tutorials SQL / MySQL Tips and Tutorials

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

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

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

One reply on “PHP, MySQL: Calculate Number of Days between 2 Dates or Number of Hours, Minutes and Seconds”

Comments are closed.