Calculate the number of days between two dates

Here’s a simple function that calculates the number of days between two dates. <?php //day’s seconds = 86400 function days_between($day_i,$month_i,$year_i,$day_f,$month_f,$year_f){ $days_in_between = (mktime(0,0,0,$month_f,$day_f,$year_f) – mktime(0,0,0,$month_i,$day_i,$year_i))/86400; return $days_in_between; } ?> //If […]

Here’s a simple function that calculates the number of days between two dates.

<?php
//day's seconds = 86400
function days_between($day_i,$month_i,$year_i,$day_f,$month_f,$year_f){
$days_in_between = (mktime(0,0,0,$month_f,$day_f,$year_f) - mktime(0,0,0,$month_i,$day_i,$year_i))/86400;
return $days_in_between;
}
?>

//If we want to calculate the days between 21/8/2009 and 1/9/2009 then
echo days_between(21,8,2009,1,9,2009);
//would give us 11

Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Check out our Collective and stay in the loop.

cody

Cody loves jQuery - he puts the magic into every web application. He is crazy about Curry dishes.

The
New
Collective

🎨✨💻 Stay ahead of the curve with handpicked, high-quality frontend development and design news, picked freshly every single day. No fluff, no filler—just the most relevant insights, inspiring reads, and updates to keep you in the know.

Prefer a weekly digest in your inbox? No problem, we got you covered. Just subscribe here.

Feedback 3

Comments are closed.
  1. When I echo:

    echo days_between(21,8,2009,1,9,2009);

    or another manually entered date(s) this function works fine. However, I need to use variables and then it gives a Warning for ‘Missing Arguement’. I tried:

    echo days_between($lt,$today);

    where:

    $today=date(“j,n,Y”);

    and $lt comes from a database result:

    $lt=date(“j,n,Y”,strtotime($row[‘life_time’]));

    If I echo $lt I get the correct database result displayed and likewise $today displays the correct day’s date.

    Any ideas what I’m doing wrong?

    Thanks!
    Craig.

  2. OK I guessed that it wanted day, month, year as separate values, so I did this:

    $tdd=date(“j”);
    $tdm=date(“n”);
    $tdy=date(“Y”);

    $std=date(“j”,strtotime($row[‘life_time’]));
    $stm=date(“n”,strtotime($row[‘life_time’]));
    $sty=date(“Y”,strtotime($row[‘life_time’]));

    echo days_between($std,$stm,$sty,$tdd,$tdm,$tdy);

    NOW it works 🙂 I don’t know if there’s a shorter way though lol