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 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

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
Previous:
Next:

Tagged with:

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

View all contributions by

Website: http://tympanus.net/codrops/author/cody/

Related Articles

Receive our bi-weekly Collective or official newsletter right in your inbox.

Which newsletter would you like to receive?

CSS Reference

Learn about all important CSS properties from the basics with our extensive and easy-to-read CSS Reference.

It doesn't matter if you are a beginner or intermediate, start learning CSS now.

Feedback 3

Comments are closed.
  1. 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. 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

Comments are closed.