[英]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个间隔而不是一个间隔:
$interval_day
$interval_night
为$interval_night
举个例子:
rotation['date_start'] = 27/07/2018 21:00:00 rotation['date_end'] = 28/07/2018 02:00:00
然后
$interval_day = 00:00:00
和$interval_night = 03:00:00
$interval_day = 00:00:00
和$interval_night = 02:00:00
每天您必须计算3个重叠:
date_start time_start
, date_end time_end
]与时间间隔[ date_start 06:00:00
: date_end 21:00:00
, date_end 21:00:00
] date_end 21:00:00
date_start time_start
, date_end time_end
]与时间间隔[ date_start 00:00:00
, date_end 06:00:00
] date_end 06:00:00
date_start time_start
, date_end time_end
)与时间间隔[ date_start 21:00:00
: date_end 23:59:59
date_start 21:00:00
, date_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.