Jun 18th

PHP Build Date Range Array

On a recent client project I was tasked with creating a chart of daily revenue from sales of, lets say, widgets. The first step to building this was to build an array of dates between two dates. I found a great little function from Mike’s Page, www.boonedocks.net that did almost exactly what I needed it to do. I need to use a few different date formats so I modified it slightly and I am re-posting it here for your use.

This function accepts (3) options, the first is the starting date which needs to be in the format ‘0000-00-00′. The second is the ending date which also needs to be in the format ‘0000-00-00′ and lastly the third is the out put date format, examples and ideas can be found in the PHP manual PHP: date – Manual.

My input dates were already in the ‘Y-m-d’ format so I didn’t bother changing this, but one could utilize the strtotime() function to make these two function input options variable.

The result is an array of dates in whichever format you define.

function get_date_range_array( $date_from, $date_to, $format = 'Y-m-d' )
{
	$date_array = array();
	$i_date_from = mktime(1, 0, 0, substr($date_from, 5, 2), substr($date_from, 8, 2),substr($date_from, 0, 4));
	$i_date_to = mktime(1, 0, 0, substr($date_to, 5, 2), substr($date_to, 8, 2),substr($date_to, 0, 4));
	if ( $i_date_to >= $i_date_from )
	{
		array_push($date_array, date($format, $i_date_from)); // first entry
		while ( $i_date_from < $i_date_to )
		{
			$i_date_from += 86400; // add 24 hours
			array_push($date_array, date($format, $i_date_from));
		}
	}
	return $date_array;
}
  1. pgl says:

    Note: this will break on daylight savings!

  2. pgl, Thanks for the heads up. I’ll have to look into this, do you have any suggestions?

Leave a Reply