Date Range to Array of Date - PHP

Mahabubur Rahman
4

In this article, I will discuss "how to get date array from given date range". Let us have the start date and end date, now we need all dates between the start and end date. How we get the date array. So you need to create a function as bellow - 

function dateRangeArray($start_date,$end_date)

{

    // takes two dates formatted as YYYY-MM-DD and creates an

    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing

    // that in the main script

    $dates = [];

    $date_from = mktime(1, 0, 0, substr($start_date, 5, 2), substr($start_date, 8, 2), substr($start_date, 0, 4));

    $date_to = mktime(1, 0, 0, substr($end_date, 5, 2), substr($end_date, 8, 2), substr($end_date, 0, 4));


    if ($date_to >= $date_from) {

        array_push($dates, date('Y-m-d', $date_from)); // first entry

        while ($date_from<$date_to) {

            $date_from += 86400; // add 24 hours

            array_push($dates, date('Y-m-d', $date_from));

        }

    }

    return $dates;

}


Now call the function as bellow -

$date_array = dateRangeArray('2021-05-01','2021-05-10');

var_dump($date_array);

The sample output - 

array(10) { [0]=> string(10) "2021-05-01" [1]=> string(10) "2021-05-02" [2]=> string(10) "2021-05-03" [3]=> string(10) "2021-05-04" [4]=> string(10) "2021-05-05" [5]=> string(10) "2021-05-06" [6]=> string(10) "2021-05-07" [7]=> string(10) "2021-05-08" [8]=> string(10) "2021-05-09" [9]=> string(10) "2021-05-10" }


["2021-05-01","2021-05-02","2021-05-03","2021-05-04","2021-05-05","2021-05-06","2021-05-07","2021-05-08","2021-05-09","2021-05-10"] 


So now we get our expected output array.


Return all dates between two dates in an array in Javascript

 

Post a Comment

4Comments
  1. It is very helpful article. Thanks for sharing this article.

    ReplyDelete
  2. i feel very happy after reading this post. i hope i will collect more information in future.
    bizboostup for know
    more

    ReplyDelete
Post a Comment