是否有这样一个函数,该函数获取两个日期之间的所有日期,比如如下函数:

getDatesFromRange( \'2010-10-01\', \'2010-10-05\' );

 要求输出结果为:

Array( \'2010-10-01\', \'2010-10-02\', \'2010-10-03\', \'2010-10-04\', \'2010-10-05\' )

该如何实现呢?

 

第一种方法:使用DatePeriod

简单但喜欢魅力:

    $period = new DatePeriod(new DateTime(\'2015-01-01\'), new DateInterval(\'P1D\'), new DateTime(\'2015-01-15 +1 day\'));
    foreach ($period as $date) {
        $dates[] = $date->format(\"Y-m-d\");
    }

    //ONLY SHOWING
    echo \'<pre>\';
    var_dump($dates);
    echo \'</pre>\';
    exit();

 

第二种方法:自定义函数法

function createRange($start, $end, $format = \'Y-m-d\') {
    $start  = new DateTime($start);
    $end    = new DateTime($end);
    $invert = $start > $end;

    $dates = array();
    $dates[] = $start->format($format);
    while ($start != $end) {
        $start->modify(($invert ? \'-\' : \'+\') . \'1 day\');
        $dates[] = $start->format($format);
    }
    return $dates;
}

使用示例:

print_r(createRange(\'2010-10-01\', \'2010-10-05\'));
/*Array
(
    [0] => 2010-10-01
    [1] => 2010-10-02
    [2] => 2010-10-03
    [3] => 2010-10-04
    [4] => 2010-10-05
)*/

print_r(createRange(\'2010-10-05\', \'2010-10-01\', \'j M Y\'));
/*Array
(
    [0] => 5 Oct 2010
    [1] => 4 Oct 2010
    [2] => 3 Oct 2010
    [3] => 2 Oct 2010
    [4] => 1 Oct 2010
)*/
收藏 打印