PHP Function to return the number of days between two dates

<?php

function dateDiff($start, $end) {

$start_ts = strtotime($start);

$end_ts = strtotime($end);

$diff = $end_ts - $start_ts;

return round($diff / 86400);

}

echo dateDiff("2006-04-05", "2006-04-01");

?>

[Edit] – Thanks Joel for pointing out the bug mentioned in the comments bellow :-)

~ by Richard@Home on March 28, 2006.

18 Responses to “PHP Function to return the number of days between two dates”

  1. Awesome! I read so many sites that did this in 100+ lines of code… I expected it to be built in to PHP. Thanks Richard!

  2. Simple and work! Thanks!

  3. Super function, thanks dude:)

  4. Nice, clean code. Thanks!

  5. Hi again. At first your script seemed perfect, but after some testing I found a bug. Your script doesn’t seem to know about March 31th.. Try to run this:

    echo dateDiff(“2008-03-29″, “2008-03-30″) . “”;
    echo dateDiff(“2008-03-29″, “2008-03-31″) . “”;
    echo dateDiff(“2008-03-29″, “2008-04-01″) . “”;
    echo dateDiff(“2008-03-29″, “2008-04-02″) . “”;

    I can’t figure out what’s wrong.

  6. Sorry about spaming, but I think I found the problem and a solution =)

    For some reason the script doesn’t give an integer for some dates. Instead you get a number like this: 2.95833333333. When you use floor() you get 2 days instead of 3. When I tried round() instead everything seems to work.

    Thanks again for this script!

  7. Thanks for the update Joel. I’ll update the code to reflect your suggestion and give you a credit :)

  8. Was looking for a quick snippet to do this… good job and thanks.

  9. hi. 1 question from me. i need to print everyday between 2 date. then what should i do?

  10. Is it possible to add some functionality to this to exclude weekend days? I’m developing a holiday request app so don’t want to include Saturday and Sunday in the calculation of the days requested. Thanks!

  11. This is great, but I think there is a rounding problem. You need to do:

    return round(($diff / 86400) + 0.5);

    Otherwise things seem to be off by a day when it’s after noon.

  12. Thanks . This is very useful

  13. $dateDiff = round((strtotime(”2008-03-29″) – strtotime(“2008-03-30″))/ 86400);

  14. Great function. It solve my one issue

  15. Nice post…thanks lot

  16. Any chance for help on leap years???

  17. What do you need help with on leap years? Since you’re converting to Unix timestamps with strtotime(), it handles it internally

  18. hey man, thanx for the function, really usefull.

Leave a Reply