假设我有以下日期范围:
2014-01-10 11:00 - 2014-01-13 15:00
我也知道我只能计算09:00到16:00之间的小时数,我如何用PHP实现这个目标?
上面的日期范围应该给我25小时(5 + 7 + 7 + 6),但不确定这样的PHP函数应该如何。
答案 0 :(得分:4)
完全未经测试,没有任何varatny
<?php
$time1 = new DateTime("11:00");
$time2 = new DateTime("15:00");
$date1 = new DateTime("2014-01-10");
$date2 = new DateTime("2014-01-13");
$start = new DateTime("9:00");
$end = new DateTime("16:00");
$maxperday = $end->diff($start)->format("%h");
$full_day_hours = ($date2->diff($date1)->format("%a")-1)*$maxperday;
$first_day_hours = min($maxperday,max(0,$end->diff($time1)->format("%h")));
$last_day_hours = min($maxperday,max(0,$time2->diff($start)->format("%h")));
$hours = $first_day_hours + $full_day_hours + $last_day_hours;
?>
编辑:现在测试,纠正了两个错误,现在似乎有效。
答案 1 :(得分:0)
我现在已经找到了解决方案,但如果只是一天,我的计算也不太满意。这是代码:
$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;