PHP Difference in Days between two Dates - Calculate Days Between Dates in PHP

Links Pages or Directory Pages
It is often handy to be able to calculate the difference between two dates or the number of days in between the two dates. The following PHP function does this in one simple line of code (the code can also be used in your PHP page rather than calling a function if speed is an issue).

function dateDiff ($d1, $d2) {
// Return the number of days between the two dates:

  return round(abs(strtotime($d1)-strtotime($d2))/86400);

}  // end function dateDiff

It doesn't matter which date is earlier or later when you pass in the date parameters. The function uses the PHP ABS() absolute value to always return a postive number as the number of days between the two dates.

Keep in mind that the number of days between the two dates is NOT inclusive of both dates. So if you are looking for the number of days represented by all the dates between and including the dates entered, you will need to add one (1) to the result of this function.

For example, the difference (as returned by the above function) between 2014-12-16 and 2014-12-21 is 5. But the number of days or dates represented by the date range 2014-12-16 - 2014-12-21 is 6.


More:   Useful PHP Scripts, Functions and Code Snippets

Related:  
Useful MySQL Commands and Code Snippets
Useful Javascript Tips and Code Snippets
Useful Perl Scripts, Functions and Code Snippets
Useful MediaWiki Extensions, Scripts, Functions and Code Snippets