PHP笔记网

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2019-08-29 18:31:51  修改时间:2024-12-22 02:30:46  分类:11.PHP基础  编辑

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

get_dates_from_range('2010-10-01', '2010-10-05');

要求输出结果为:

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

该如何实现呢?

第一种方法:使用DatePeriod

<?php
$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");
}
    
print_r($dates);

 

第二种方法:自定义函数法(推荐)

<?php
function create_range($start, $end, $format = 'Y-m-d') {
    $start  = new DateTime($start);
    $end    = new DateTime($end);
    $invert = $start > $end;
    
    $dates   = [];
    $dates[] = $start->format($format);
    while ($start != $end) {
        $start->modify(($invert ? '-' : '+') . '1 day');
        $dates[] = $start->format($format);
    }
    
    return $dates;
}

使用示例:

print_r(create_range('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(create_range('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
)*/