d
Amit DhamuSoftware Engineer
 

Loop Between Date Range

2 minute read 00000 views

Say you have two dates - a start date and an end date and you want to loop through and show the dates in between that range, try the following function which will take a start date and end date and output the results into an array.

$start = '2012-01-01 12:00:00';
$end = '2012-08-01 12:00:00';

function dateRange($first, $last, $step = '+1 month', $format = 'Y-m-d H:i:s') {
    $dates = [];
    $current = strtotime($first);
    $last = strtotime($last);

    while ($current <= $last) {
        $dates[] = date($format, $current);
        $current = strtotime($step, $current);
    }
    return $dates;
}

// I want to print out the dates in between my range on a monthly basis
echo dateRange($start, $end);

Array
(
    [0] => 2012-01-01 12:00:00
    [1] => 2012-02-01 12:00:00
    [2] => 2012-03-01 12:00:00
    [3] => 2012-04-01 12:00:00
    [4] => 2012-05-01 12:00:00
    [5] => 2012-06-01 12:00:00
    [6] => 2012-07-01 12:00:00
    [7] => 2012-08-01 12:00:00
)

// Alternatively, if you wanted to show each day between your date range
echo dateRange($start, $end, '+1 day');