Home >Backend Development >PHP Tutorial >How to Generate an Array of Dates Between Two Given Dates in PHP?

How to Generate an Array of Dates Between Two Given Dates in PHP?

DDD
DDDOriginal
2024-12-30 08:09:10181browse

How to Generate an Array of Dates Between Two Given Dates in PHP?

Generate an Array of Dates Between Two Specified Dates in PHP

This PHP code snippet helps you attain a crucial task in date manipulation: generating an array containing all dates within a specified range. This code successfully achieves this by converting the given date range into an array of dates.

Expected Input

The expected input for this code is a pair of dates in the format 'YYYY-MM-DD'. For example, if you want to generate an array of dates between October 1st, 2010, and October 5th, 2010, the input would be:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output

The expected output is an array containing all dates within the specified range. In the example above, the output would be:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

Solution

This code employs two approaches to generate an array of dates between two specified dates:

  1. Using a Loop:

    • Create a new DateTime object for the start date.
    • Iterate from the start date to the end date, incrementing the day by one each iteration.
    • Add each date to an array.
  2. Using the DatePeriod Class:

    • Create a new DatePeriod object with the start and end dates and a day interval.
    • Iterate over the DatePeriod object using a foreach loop.
    • Convert each DateTime object to a string in the desired format.

Code Implementation

function getDatesFromRange($startDate, $endDate) {
    $dates = array();

    // Convert the start and end dates to DateTime objects
    $startDateObj = new DateTime($startDate);
    $endDateObj = new DateTime($endDate);

    // Iterate from the start date to the end date, incrementing the day by one each iteration
    while ($startDateObj <= $endDateObj) {
        $dates[] = $startDateObj->format('Y-m-d');
        $startDateObj->add(new DateInterval('P1D'));
    }

    return $dates;
}

Example Usage

$dates = getDatesFromRange('2010-10-01', '2010-10-05');
print_r($dates);

Output

Array ( [0] => 2010-10-01 [1] => 2010-10-02 [2] => 2010-10-03 [3] => 2010-10-04 [4] => 2010-10-05 )

The above is the detailed content of How to Generate an Array of Dates Between Two Given Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn