PHP: Get an array of dates between two dates

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Frequently in web development with PHP, there’s a need to calculate a range of dates between two specified dates. This can be used for generating reports, creating booking date ranges, or for storing an array of sequential dates. In this tutorial, we’ll explore several methods to achieve this in PHP.

Using DateTime and DateInterval

The DateTime and DateInterval classes provide a powerful combination to work with dates in an object-oriented manner. Here’s a basic example of how to get an array of dates between two dates:


$start = new DateTime('2021-01-01');
$end = new DateTime('2021-01-10');
//Create a DateInterval object with a 1 day interval
$interval = new DateInterval('P1D');

$dates = [];
for($i = $start; $i <= $end; $i->add($interval)){
  $dates[] = $i->format('Y-m-d');
}
print_r($dates);

This basic example simply creates a DateTime object for both the start and end date, and in a loop adds a new date interval (in this case, 1 day), until it reaches the end date. Then, each date is formatted as a string and added to an array, which can be used as needed.

Using the DatePeriod Class

A more advanced and succinctway to achieve the same result is by using the DatePeriod class in PHP:


$start = new DateTime('2021-01-01');
$end = (new DateTime('2021-01-10'))->modify('+1 day');
$interval = new DateInterval('P1D');

$period = nre DatePeriod($start, $interval, $end);
foreach ($period as $date) {
  $dates[] = $date->format('Y-m-d');
}
print_r($dates);

The DatePeriod creates a period of time where you can iterate over each interval. For example, a DatePeriod with a one-day interval, iterating over it will generate one DateTime Object for each day, until the end date is reached. Note that the $end date has been modified to include the last date in the range.

Handling Different Intervals

We’ve so far considered daily intervals, but PHP’s DateInterval can handle a variety of intervals such as weekly, monthly, or even yearly intervals. Here’s how you can modify the previous examples to accept different intervals:


$intervalSpec = 'P1W'; // 1 week
$interval = new DateInterval($intervalSpec);

// Use either the for loop or the DatePeriod as previously demonstrated

Dealing with Large Date Ranges

When dealing with very large date ranges, keeping the memory usage efficient becomes important. Instead of storing all dates in an array, you might opt to yield each date from a generator function if PHP 5.5 or higher is used:


function createDateRangeGenerator($start, $end, $intervalSpec = 'P1D') {
  $start = new DateTime($start);
  $end = new DateTime($end);
  $interval = new DateInterval($intervalSpec);

  $period = new DatePeriod($start, $interval, $end);
  foreach ($period as $date) {
    yield $date->format('Y-m-d');
  }
}

// Usage
foreach (createDateRangeGenerator('2021-01-01', '2021-01-10') as $date) {
  echo $date . "\n";
}

This generator functions create a date range on-the-fly without accumulating the entire array in memory.

Edge Case Handling

When building utility functions to retrieve date ranges, consider edge cases such as:

  • What if the start date is after the end date?
  • How to handle time zones?
  • Should the end date be included or excluded from the range?

Incorporating these considerations make your code more robust and predictable. It’s a good practice to throw exceptions or return a meaningful error message when such edge cases are encountered.

Conclusion

Generating an array of dates between two specific dates in PHP is a common task that can be elegantly solved using the DateTime, DateInterval, and DatePeriod classes. These provide an object-oriented approach to date and time manipulation. Remember to always think of edge cases while implementing such features, and your date-related functionalities will be both powerful and reliable.