PHP date range from two dates

By August 23, 2017PHP, Programming

This is the custom PHP by this one’s can get date range from two different dates in PHP.

Example :

function getDatesFromRange($start, $end, $format = 'Y-m-d') {
        $array = array();
        $interval = new DateInterval('P1D');

        $realEnd = new DateTime($end);
        $realEnd->add($interval);

        $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

        foreach ($period as $date) {
            $array[] = $date->format($format);
        }

        return $array;
    }

Function call

$date =  getDatesFromRange('2010-03-21', '2010-03-29', $format = 'Y-m-d');

Just pass the two different dates and the date format which you want the output.In the above call we are calling getDatesFromRange defined above and we want the result in YYY-MM-DD format.

Output

Array ( 
        [0] => 2010-03-21 
        [1] => 2010-03-22
        [2] => 2010-03-23 
        [3] => 2010-03-24 
        [4] => 2010-03-25 
        [5] => 2010-03-26 
        [6] => 2010-03-27 
        [7] => 2010-03-28 
        [8] => 2010-03-29 
       )
Pankaj Singh Sugara

Author Pankaj Singh Sugara

More posts by Pankaj Singh Sugara