2023年3月

利用DatePeriod 类获取两个日期之间的所有日期

官方文档:https://www.php.net/manual/zh/class.dateperiod.php
DatePeriod 类表示一个时间周期,时间周期内允许对一组日期和时间进行迭代,在指定的时间间隔内定期重复。
注意:8.2 新增 DatePeriod::INCLUDE_END_DATE

/**
 * 获取两个日期间的所有日期
 * @param $startDate 2023-04-01
 * @param $endDate  2023-04-19
 * @param $format
 * @param $last 是否包含最后一天
 * @return array
 * @throws Exception
 */
function getDateRange($startDate, $endDate, $format = "Y-m-d", $last=true, $first=true)
{
    $begin = new DateTime($startDate);
    $end = new DateTime($endDate);
    if($last){
        $end->modify('+1 day');
    }
    $interval = new DateInterval('P1D'); // 1 Day
    $exclude = 0;
    if(!$first){
        $exclude = DatePeriod::EXCLUDE_START_DATE;
    }
    $dateRange = new DatePeriod($begin, $interval, $end, $exclude);
    $range = [];
    foreach ($dateRange as $date) {
        $range[] = $date->format($format);
    }
    return $range;
}
PHP