PHP Code to generate Date Range

To generate a date range in PHP, where you define a start date and an end date, and then create an array or list of all dates between (and including) those two dates, you can use the following approach.

Example: PHP Code for Generating a Date Range

<?php
function createDateRange($startDate, $endDate, $format = "Y-m-d") {
    $dates = [];

    // Convert the start and end dates to DateTime objects
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $end = $end->modify('+1 day'); // Include end date

    // Create a DatePeriod with daily intervals
    $interval = new DateInterval('P1D');
    $dateRange = new DatePeriod($start, $interval, $end);

    // Loop through the DatePeriod and add each date to the array
    foreach ($dateRange as $date) {
        $dates[] = $date->format($format);
    }

    return $dates;
}

// Example usage
$startDate = '2024-08-01';
$endDate = '2024-08-10';
$dateRange = createDateRange($startDate, $endDate);

// Print the date range
foreach ($dateRange as $date) {
    echo $date . "<wp-br>";
}
?>

 

Explanation:

  1. Function Definition:
  • createDateRange($startDate, $endDate, $format = "Y-m-d"): The function takes a start date, an end date, and an optional date format (defaulting to Y-m-d).
  • Inside the function, the start and end dates are converted into DateTime objects.
  1. Date Modification:
  • $end = $end->modify('+1 day');: This modification is done to include the end date in the generated range.
  1. DatePeriod and Interval:
  • DateInterval('P1D') defines a 1-day interval, meaning the DatePeriod will generate each day in the range.
  • DatePeriod($start, $interval, $end): Creates a period from the start date to the end date with the defined interval.
  1. Looping Through Dates:
  • A loop iterates through the DatePeriod object, formatting each date according to the provided format and adding it to the $dates array.
  1. Example Usage:
  • The function is called with a start date (2024-08-01) and an end date (2024-08-10).
  • The result is an array of dates from August 1, 2024, to August 10, 2024, which is then printed.