![]() |
|
Snippets |
|
Sometimes you need a list of the dates between two dates.
/** * Returns an array with the dates between to dates given. * * @link http://us3.php.net/manual/en/function.date.php#AEN25217 * * @param mixed $startdate Timestamp or strtotime() recognizeable string * @param mixed $enddate Timestamp or strtotime() recognizeable string * @param string[optional] $format date() format string * @return mixed Array of timestamps or dates if given format */ public static function dates_between($startdate, $enddate, $format=null){ (is_int($startdate)) ? 1 : $startdate = strtotime($startdate); (is_int($enddate)) ? 1 : $enddate = strtotime($enddate); if($startdate > $enddate){ return false; //The end date is before start date } while($startdate < $enddate){ $arr[] = ($format) ? date($format, $startdate) : $startdate; $startdate += 86400; } $arr[] = ($format) ? date($format, $enddate) : $enddate; return $arr; }
You can give it a timestamp or a string date. It will use date() to format the output if given a $format.
Comments on this snippet
As an alternative, the PHP range function introduced a 'step' argument in v5, so if you aren't bothered about date formatting, you ought to be able to replace everything from the last 'while' loop with:
return range($startdate, $enddate, 86400);
range will automatically work backward if $enddate is lower than $startdate, but if you don't want that behaviour you can either switch the dates around or return false, depending on your business logic (I'm personally allergic to returning errors when unnecessary, but I can see how returning false might be correct in some cases). If you want optional formatting, then you can use array_map:
$arr = range($startdate,$enddate,86400); return $format ? array_map('dateformat_long',$arr) : $arr;
(and then define dateformat_long as something like) function array_dateformat($value) { return date($value, 'D jS F Y'); }