获取两个日期之间的间隔日夜

时间:2018-07-27 10:44:59

标签: php date

我正在创建一种算法,该算法必须在两个日期之间返回两个间隔:

$interval_day (between 6am and 9pm)
$interval_night (between 9pm and 6am)

目前,我设法确定了这两个日期之间的总体间隔。但是,我现在需要白天的间隔和夜间的间隔。

这是我获取两个日期之间每天间隔的代码:

foreach($period as $p => $v){
            $day = $v->format('Y-m-d');
            $interval = 0;
                foreach($rotations as $rotation){
                    // Get the day of each dates
                    $date_start = explode(" ", $rotation['date_start'])[0];
                    $date_end = explode(" ", $rotation['date_end'])[0];
                    if($date_start == $date_end){
                        // += interval between the two dates
                        $interval += strtotime($rotation['date_end']) - strtotime($rotation['date_start']);
                    }else if($date_start == $day){
                        // += interval between the start date and midnight
                        $interval += strtotime($day." 23:59:59") - strtotime($rotation['date_end']);
                    }else if($date_end == $day){
                        // += interval between midnight and the end date
                        $interval += strtotime($rotation['date_end']) - strtotime($day." 00:00:00");
                    }
                }
}

我希望对你很清楚

我现在想要的是获得2个间隔而不是一个间隔:

  • 在1上午6点至晚上9点之间的日期中,间隔为$interval_day
  • 在9 pm和6 am之间的日期为$interval_night的1个间隔

例如:

rotation['date_start'] = 27/07/2018 21:00:00 rotation['date_end'] = 28/07/2018 02:00:00

然后

  • 27/07/2018:

$interval_day = 00:00:00$interval_night = 03:00:00

  • 28/07/2018:

$interval_day = 00:00:00$interval_night = 02:00:00

1 个答案:

答案 0 :(得分:1)

每天您必须计算3个重叠:

  1. 在间隔[date_start time_start之间重叠, 给定日期的date_end time_end]和间隔[date_start 06:00:00date_end 21:00:00]
  2. 给定日期的间隔[date_start time_startdate_end time_end]和间隔[date_start 00:00:00date_end 06:00:00]之间重叠
  3. 给定日期的间隔[date_start time_startdate_end time_end)和间隔[date_start 21:00:00date_end 23:59:59]之间重叠...

为此,请使用以下公式:

overlap = MAX(0,end_1 - start_1 - MAX(0,end_1 - end_2) - MAX(0,start_2 - start_1))

该公式需要整数-即UNIX时间戳。