PHP dates between two dates tutorial

For any calendar or time management application it is useful to be able to generate dates between two given dates. Doing it is actually quite easy. Just see the code below for the function.

function getDaysInBetween($start, $end) {
// Vars
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start); // Start as time
$eTime = strtotime($end); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();

// Get days
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));

// Return days
return $days;

The above code accepts a start and end date that is understood by strtotime. The function returns an array of days, the format of which is specified in the $format variable which accepts all formats used by date.

To use the function simply call it like getDaysInBetween('2009-03-01', '2009-03-06'); Please note that the results are inclusive of the original start and end dates.


Ongo said...

Thx man, this script is really working.. GBU


Thanxs man, Good job!

Post a Comment