nicklasos
5/8/2015 - 12:26 PM

php date range

php date range

<?php
/**
 * Example:
 *
 * $data = dateRange(
 *    'midnight 29 days ago',
 *    'tomorrow',
 *    '+1 day',
 *    function (DateTime $date) use ($data) {
 *       return $this->doSomething(
 *          $date->getTimestamp(),
 *          $date->modify('+1 day')->getTimestamp()
 *       );
 *    }
 * );
 *
 * var_dump($data);
 *
 * @param string $from
 * @param string $to
 * @param string $step
 * @param callable $callback
 * @return array
 */
function dateRangeMap($from, $to, $step, callable $callback)
{
    return array_map($callback, iterator_to_array(new DatePeriod(
        new DateTime($from, new DateTimeZone('UTC')),
        DateInterval::createFromDateString($step),
        new DateTime($to, new DateTimeZone('UTC'))
    )));
}