Clue Mediator

How to get all Dates between two Dates in PHP

๐Ÿ“…July 6, 2022
๐Ÿ—PHP

Today, we will show you how to get all Dates between two Dates in PHP. Here, we get the all dates array between the given start and end date which can be used to get reports between two dates by daily, weekly, monthly, or yearly. we explain two different methods with simple example to return the datetime" title="DateTime">dates in array.

Checkout more articles on PHP

  • cors-for-multiple-domains-in-php" title="Enable CORS for multiple domains in PHP">Enable CORS for multiple domains in PHP
  • QR code using PHP">Generate QR code using PHP
  • bootstrap-modal-with-ajax-php-and-mysql" title="Load dynamic content in Bootstrap Modal with AJAX, PHP and MySQL">Load dynamic content in Bootstrap Modal with AJAX, PHP and MySQL
  • recaptcha-v3-in-php" title="Google reCAPTCHA v3 in PHP">Google reCAPTCHA v3 in PHP
  • xml-to-json-in-php" title="Convert XML to JSON in PHP">Convert XML to JSON in PHP

Ways to get all dates between two dates

  1. Using strtotime() function
  2. Using date interval class

1. Using strtotime() function

In this method, we will use the strtotime() function to get the all dates between two dates.

We will create a function which contains only start date and end date parameters, that returns the array of dates between two dates.

<!--?php
function getBetweenDates($startDate, $endDate) {
    $rangArray = [];<p-->

    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    for ($currentDate = $startDate; $currentDate <= $endDate; $currentDate += (86400)) {
        $date = date('Y-m-d', $currentDate);
        $rangArray[] = $date;
    }

    return $rangArray;
}
$dates = getBetweenDates('2022-07-01', '2022-07-09');
print_r($dates);
?>

2. Using date interval class

Letโ€™s use the following code to get the list of dates between two dates using date interval class.

<!--?php
function getBetweenDates($startDate, $endDate) {
    $array = array();
    $interval = new DateInterval('P1D');<p-->

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

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

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

    return $array;
}
$dates = getBetweenDates('2022-07-01', '2022-07-09');
print_r($dates);
?>

Output

You will get the following output.

Array
(
    [0] => 2022-07-01
    [1] => 2022-07-02
    [2] => 2022-07-03
    [3] => 2022-07-04
    [4] => 2022-07-05
    [5] => 2022-07-06
    [6] => 2022-07-07
    [7] => 2022-07-08
    [8] => 2022-07-09
)

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚