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:
Using a Loop:
Using the DatePeriod Class:
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!