繁体   English   中英

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

[英]Get Interval Night and Day per Day between two dates

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

$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
  • 1个间隔,用于在晚上9点至早上6点之间的日期, $interval_night$interval_night

举个例子:

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

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

  1. 给定日期的时间间隔[ date_start time_startdate_end time_end ]与时间间隔[ date_start 06:00:00 : date_end 21:00:00date_end 21:00:00 ] date_end 21:00:00
  2. 给定日期的时间间隔[ date_start time_startdate_end time_end ]与时间间隔[ date_start 00:00:00date_end 06:00:00 ] date_end 06:00:00
  3. 给定日期的时间间隔[ date_start time_startdate_end time_end )与时间间隔[ date_start 21:00:00 : date_end 23:59:59 date_start 21:00:00date_end 23:59:59 ] date_end 23:59:59

为此,请使用以下公式:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM