joshtronic

in Software Development #PHP

How to generate a date range with PHP

From time to time I need to loop through a date range. One approach is to generate a start date and an end date and then add 1 day to the start date until it reaches the end date (or whatever interval you want to increment by). This works wonders thanks to strtotime:

$start = '2014-12-07';
$end   = '2014-12-31';

while ($start <= $end) { // Do something with the date here...

// Increment the date $start = strtotime($start . ' +1 day'); }

If you wanted to do this in a more object-oriented way, and you are using PHP 5.3+, you can leverage the DatePeriod class. Combined with the DateTime and DateInterval classes you are able to achieve this:

$start = new DateTime('2014-12-07');
$end   = new DateTime('2014-12-31');
$range = new DatePeriod($start, new DateInterval('P1D'), $end);

foreach ($range as $date) { // Do something with the date here... }

The code's a bit shorter but is probably more memory intensive due to the use of objects. Like most things in PHP-land, the choice is yours based on how you want to implement things. Got another way to generate a date range? Comment below!