How to get all dates between 2 dates in PHP

1 Answer

0 votes
/**
 * Generates all dates between a start and end date inclusive.
 * Uses native DatePeriod and DateTimeImmutable for robust, modern PHP date handling.
 * 
 * @param string $startDateStr Start date in "YYYY-MM-DD" format.
 * @param string $endDateStr   End date in "YYYY-MM-DD" format.
 * @return array               An array of date strings in "YYYY-MM-DD" format, or an empty array on error.
 */
function getDatesBetween(string $startDateStr, string $endDateStr): array {
    try {
        // 1. Parse into immutable DateTime objects (prevents accidental date modifications)
        $startDate = new DateTimeImmutable($startDateStr);
        $endDate = new DateTimeImmutable($endDateStr);

        // 2. Validate that the date range is logically sound
        if ($startDate > $endDate) {
            throw new InvalidArgumentException("Start date cannot be after the end date.");
        }

        // 3. Create a 1-day interval
        $interval = new DateInterval('P1D');

        // 4. Create a DatePeriod including the end date (supported in PHP 8.2+)
        // If you are on an older PHP version (< 8.2), you can add 1 day to the end date instead.
        $period = new DatePeriod(
            $startDate,
            $interval,
            $endDate,
            DatePeriod::INCLUDE_END_DATE
        );

        $dates = [];
        
        // 5. Iterate through the period and format each date
        foreach ($period as $date) {
            $dates[] = $date->format('Y-m-d');
        }

        return $dates;

    } catch (Exception $e) {
        // Handle malformed strings or invalid calendar dates (e.g., "2026-02-31")
        error_log("Date Generation Error: " . $e->getMessage());
        return [];
    }
}

// --- Example Usage ---
$start = "2026-02-26";
$end = "2026-03-02";

$dates = getDatesBetween($start, $end);

echo "Dates between $start and $end:\n";
foreach ($dates as $date) {
    echo $date . "\n";
}


/*
run:

Dates between 2026-02-26 and 2026-03-02:
2026-02-26
2026-02-27
2026-02-28
2026-03-01
2026-03-02

*/

 



answered 4 days ago by avibootz
...