可以说我有以下日期范围:
2014-01-10 11:00-2014-01-13 15:00
我也知道我只能计算09:00-16:00之间的小时数,如何使用PHP做到这一点?
上面的日期范围应该给我25个小时(5 + 7 + 7 + 6),但是不确定这样的PHP函数应该看起来如何。
我现在已经提出了一个解决方案,但是如果只是一天,我对我的计算不太满意。这是代码:
$startDate = strtotime("2014-01-22 15:00");
$endDate = strtotime("2014-01-24 18:00");
$time1 = new DateTime(date("H:i", $startDate));
$time2 = new DateTime(date("H:i", $endDate));
$date1 = new DateTime(date("Y-m-d", $startDate));
$date2 = new DateTime(date("Y-m-d", $endDate));
$start = new DateTime("11:00");
$end = new DateTime("18:00");
$maxPerDay = $end->diff($start)->format("%h") != 0 ? $end->diff($start)->format("%h") : 24;
$days = $date2->diff($date1)->format("%a");
$hours = 0;
//Is it just one day and is time intersecting?
if($days == 0 && ($start <= $time2 && $time1 <= $end)){
$hours = $maxPerDay;
if($start < $time1 || $end > $time2){
if($time1 < $start){
$hours = $maxPerDay - $time2->diff($end)->format("%h");
}else if($time2 > $end){
$hours = $maxPerDay - $time1->diff($start)->format("%h");
}else{
$hours = $time1->diff($time2)->format("%h");
}
}
}else if($days > 0){
$firstDay = 0;
$lastDay = 0;
if($time1 < $end){
$firstDay = $time1 < $start ? $maxPerDay : $maxPerDay - $time1->diff($start)->format("%h");
}
if($time2 > $start){
$lastDay = $time2 > $end ? $maxPerDay : $maxPerDay - $time2->diff($end)->format("%h");
}
$hours = $lastDay + $firstDay + ($days - 1) * $maxPerDay;
}
echo $hours;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句