PHP Function : To get an array of all dates between two dates

In this tutorial I am going to share simple php function which give you result of dates array between given start and end date. It’ll be helpful to display reports between two dates by daily, weekly, monthly or yearly. You just only have to pass statdate, enddate and date format in below function and it’ll give you array list of between two dates.

function createDateRange($startDate, $endDate, $format = "d-m-Y")
{
    $begin = new DateTime($startDate);
    $end = new DateTime($endDate);
 
    $interval = new DateInterval('P1D'); // 1 Day
    $dateRange = new DatePeriod($begin, $interval, $end);
 
    $range = [];
    foreach ($dateRange as $date) {
        $range[] = $date->format($format);
    }
 
    return $range;
}

Where:

  • Returns every date between two dates as an array
  • $startDate the start of the date range
  • $endDate the end of the date range
  • $format DateTime format, default is d-m-Y
  • return array returns every date between $startDate and $endDate, formatted as “d-m-Y”



The above function return an array of all dates between two dates, you use the function like this:

createDateRange("01-01-2019", "31-01-2019");

Output:

Array
(
    [0] => 01-01-2019
    [1] => 02-01-2019
    [2] => 03-01-2019
    [3] => 04-01-2019
    [4] => 05-01-2019
    [5] => 06-01-2019
    [6] => 07-01-2019
    [7] => 08-01-2019
    [8] => 09-01-2019
    [9] => 10-01-2019
    [10] => 11-01-2019
    [11] => 12-01-2019
    [12] => 13-01-2019
    [13] => 14-01-2019
    [14] => 15-01-2019
    [15] => 16-01-2019
    [16] => 17-01-2019
    [17] => 18-01-2019
    [18] => 19-01-2019
    [19] => 20-01-2019
    [20] => 21-01-2019
    [21] => 22-01-2019
    [22] => 23-01-2019
    [23] => 24-01-2019
    [24] => 25-01-2019
    [25] => 26-01-2019
    [26] => 27-01-2019
    [27] => 28-01-2019
    [28] => 29-01-2019
    [29] => 30-01-2019
)

Posted in: PHP

One Reply to “PHP Function : To get an array of all dates between two dates”

  1. Any db will offer a between function for reporting date ranges, why need for PHP?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.