Search code examples
phpdatedate-arithmetic

Calculate all dates between 2 dates in php?


I have 2 dates

$st_date = '2012-07-20';
$ed_date = '2012-07-27';

I want to display all dates from $st_date to $ed_date As:

2012-07-20
2012-07-21
2012-07-22
2012-07-23
2012-07-24
2012-07-25
2012-07-26
2012-07-27

I thought first count difference, run foreach < count, and add $i day to $st_date.
But i don't want loop, it increases code. Any of direct date() which return an array of all-dates.


Solution

  • Without loop using range() & array_map() :

    EDIT: a little mistake, you have to jump 86400, because 1 day = 86400 seconds, so the code should be fine now :)

        $st_date = '2012-07-20';
        $ed_date = '2012-07-27';
        $dates = range(strtotime($st_date), strtotime($ed_date),86400);
        $range_of_dates = array_map("toDate", $dates);
        print_r($range_of_dates);
        function toDate($x){return date('Y-m-d', $x);}
    
    ?>