// you’re reading...

PHP

Get Days Between Two Dates Using PHP

This is a simple snippet of code that will return an array of days between two dates.

Read on for a little more info…

<?php
function GetDays($sStartDate, $sEndDate){
  // Firstly, format the provided dates.
  // This function works best with YYYY-MM-DD
  // but other date formats will work thanks
  // to strtotime().
  $sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
  $sEndDate = gmdate("Y-m-d", strtotime($sEndDate));

  // Start the variable off with the start date
  $aDays[] = $sStartDate;

  // Set a 'temp' variable, sCurrentDate, with
  // the start date - before beginning the loop
  $sCurrentDate = $sStartDate;

  // While the current date is less than the end date
  while($sCurrentDate < $sEndDate){
    // Add a day to the current date
    $sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));

    // Add this new day to the aDays array
    $aDays[] = $sCurrentDate;
  }

  // Once the loop has finished, return the
  // array of days.
  return $aDays;
}
?>

Usage:

$aDays = GetDays('5th Feb 2007', '10th Feb 2007');

You can use most date formats, such as:

GetDays('2007-01-01', '2007-01-31');

or

GetDays('19-02-2007', '25-02-2007');

Whatever strtotime can handle, you can pass to this function.

Hope it helps!

Discussion

8 comments for “Get Days Between Two Dates Using PHP”

  1. Saint!

    Posted by Ben McDougal | August 18, 2008, 9:53 am
  2. Great and very usefull script..thank you

    Posted by Manish | December 23, 2008, 3:34 pm
  3. Thx buddy i really enjoyed this function… as i truely req. it in my proj….

    Again thanking u….

    Posted by Javed | January 5, 2009, 5:24 am
  4. Kudos to you dude. that saved me some time! thank you!

    Posted by bernard | January 21, 2009, 4:27 pm
  5. Thank you! This is exactly what I had been looking for.

    Posted by rob | March 19, 2009, 11:24 pm
  6. This is exactly what i want..but it does not work well…i alway get this error

    Fatal error: Maximum execution time of 30 seconds exceeded

    i don't know why..!!!!i understand the code well but…
    thanks alot..thanks for any help…

    Posted by yamama | April 3, 2009, 4:41 pm
  7. by the way….i use a logical two days!!!!!!!!!! the start date less than the end date and between them not more than 25 days..:(

    Posted by yamama | April 3, 2009, 4:43 pm
  8. Thanx a lot for the function

    Posted by Midhun | May 14, 2009, 9:46 am

Post a comment

Most Emailed