根据两个日期获取连续的时间段

php

浏览数:335

2019-1-8

/**
     * 根据开始和结束时间获取所有连续的时间段
     * @param string $startDay 开始日期 格式:Y-m-d
     * @param string $endDay 开始日期 格式:Y-m-d
     * @param string $dateFormat
     * @return array
     */
    public static function getContinuesDayByRange($startDay, $endDay, $dateFormat = 'Y-m-d') {
        $timeLabel = [];
        if(strtotime($startDay) > strtotime($endDay)){
            $tmp = $startDay;
            $endDay = $tmp;
            $startDay = $endDay;
        }
        if($startDay == $endDay){
            array_push($timeLabel,$startDay);

            $startTime = strtotime($startDay." 00:00:00");
            $endTime = strtotime($endDay." 23:59:59");
            $timeLabel =  [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'time_label' => $timeLabel,
            ];
            return $timeLabel;
        }

        $targetDay = $startDay;
        while ($targetDay != $endDay){
            array_push($timeLabel,$targetDay);
            $targetDay = date($dateFormat,strtotime("$targetDay +1 day"));
        }

        array_push($timeLabel,$endDay);

        //增加
        $startTime = strtotime($startDay." 00:00:00");
        $endTime = strtotime($endDay." 23:59:59");
        $timeLabel =  [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'time_label' => $timeLabel,
        ];
        return $timeLabel;
    }