How To Return All Dates Between Two Dates

To return all dates between two given dates in PHP, you can use the DateTime class along with a loop to iterate through each date and store them in an array. Let’s illustrate this process in detail.

  1. Create DateTime Objects: First, create DateTime objects for the start and end dates.
$start = new DateTime('2024-03-31');
$end = new DateTime('2024-04-09');
  1. Initialize an Empty Array: Create an empty array to store the dates between the start and end dates.
$dateArray = array();
  1. Loop Through Dates: Iterate through each date between the start and end dates, and add them to the array.
while ($start <= $end) {
    $dateArray[] = $start->format('Y-m-d');
    $start->modify('+1 day');
}
  1. Return the Array of Dates: Finally, return the array containing all the dates between the given range.
return $dateArray;

Putting it all together, here’s the complete function:

function getDatesBetween($startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $dateArray = array();

    while ($start <= $end) {
        $dateArray[] = $start->format('Y-m-d');
        $start->modify('+1 day');
    }

    return $dateArray;
}

// Usage
$startDate = '2024-03-31';
$endDate = '2024-04-09';
$datesBetween = getDatesBetween($startDate, $endDate);
print_r($datesBetween);

This function will output an array containing all the dates between March 31, 2024, and April 9, 2024, inclusive. You can modify the date format according to your preference by adjusting the format parameter in the format() method. Additionally, you can customize the start and end dates based on your requirements by passing different date strings to the function.

Leave a Reply