Php 获取两个日期之间的昼夜间隔
我正在创建一个算法,该算法必须在两个日期之间返回两个间隔:Php 获取两个日期之间的昼夜间隔,php,date,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 $rot
$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");
}
}
}
目前,我设法得到了当天这两个日期之间的总间隔时间。但是,我现在需要白天和夜间的休息时间
下面是我用来获取两个日期之间每天的间隔的代码:
$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");
}
}
}
我希望你明白
我现在想要的是得到两个间隔,而不是一个:
- 上午6点到晚上9点之间的日期间隔为1天
$interval\u day
- 晚上9点到早上6点之间的日期间隔为1次,如
$interval\u night
轮换['date_start']=2018年7月27日21:00:00
轮换['date_end']=2018年7月28日02:00:00
然后
- 2018年7月27日:
$interval\u day=00:00:00
和$interval\u night=03:00:00
- 2018年7月28日:
$interval\u day=00:00:00
和$interval\u night=02:00:00
每天必须计算3个重叠:
日期\u开始时间\u开始时间
之间重叠,
给定日期和时间间隔[date\u start 06:00:00
,date\u end 21:00:00
]date\u start time\u start
,date\u end time\u end
]与间隔[date\u start 00:00:00
,date\u end 06:00:00
]日期\开始时间\开始
,日期\结束时间\结束
)与间隔[日期\开始21:00:00
,日期\结束23:59:59
]overlap = MAX(0,end_1 - start_1 - MAX(0,end_1 - end_2) - MAX(0,start_2 - start_1))
公式需要整数,即UNIX时间戳。您好,非常感谢您的回答。我从未使用过重叠函数,因此我不理解您的公式。我正在互联网上寻找更多信息。非常感谢,您需要在给定的一天内和
间隔内同时占用的时间量(或间隔\u晚
)-这意味着多少interval\u day
与给定的一天重叠。如果你在纸上画一个间隔,然后在第一个间隔内画另一个间隔,公式非常简单。如果你从第一个间隔的持续时间中减去左段和右段,你将得到重叠的量。非常感谢我的理解