不是很漂亮的代碼,但它的工作原理:
注:日期由年有限
<?php
// test values
$start_date = mktime(9,0,0,5,5,2016); // 5-may-2016 (Thursday)
$end_date = mktime(18,0,0,5,20,2016); // 20-may-2016 (Saturday)
// count days between dates
$days_between = date('z',$end_date) - date('z', $start_date) + 1;
// guessing how many weekends days can be
$weekdays = floor($days_between/7)*3;
// get weekday nubmer 1-monday..7-sunday
$sday = date('N',$start_date);
$eday = date('N',$end_date);
// initialize counters
$surge = 0;
$normal = 0;
if ($days_between >=7) {
// correct weekends days count
// when we have more than 1 week difference
switch ($sday) {
case 7:
$weekdays--;
case 6:
$weekdays--;
}
switch ($eday) {
case 7:
$weekdays++;
case 6:
$weekdays++;
case 5:
$weekdays++;
}
} else {
// correct weekends days count
// when we have less than 1 week difference
switch ($sday) {
case 1:
case 2:
case 3:
case 4:
case 5:
$weekdays++;
case 6:
$weekdays++;
case 7:
$weekdays++;
}
switch ($eday) {
case 5:
$weekdays--;
case 6:
$weekdays--;
}
}
// remember start and end hours
$shour = date('G', $start_date);
$ehour = date('G', $end_date);
if ($sday == $eday) {
// we're start and end at the same day
if (in_array($sday, array(5,6,7))) {
$surge += $ehour - $shour;
} else {
$normal += $ehour - $shour;
}
} else {
$first_day_hours = 24 - $shour;
$last_day_hours = $ehour;
// decrease counter by two, because
// the first and last days process separately
$days_between -= 2;
if (in_array($sday, array(5,6,7))) {
$surge += $first_day_hours;
$weekdays--;
} else {
$normal += $first_day_hours;
}
if (in_array($eday, array(5,6,7))) {
$surge += $last_day_hours;
$weekdays--;
} else {
$normal += $last_day_hours;
}
if ($days_between>0) {
$surge += 24 * $weekdays;
$normal += 24 * ($days_between - $weekdays);
}
}
echo 'Normal: '.$normal.PHP_EOL;
echo ' Surge: '.$surge.PHP_EOL;
代碼接近信號源(使用循環):
注:日期不限
<?php
// test values
$start_date = mktime(9,0,0,5,5,2016);
$end_date = mktime(18,0,0,5,20,2016);
// remember start and end hours
$shour = date('G', $start_date);
$ehour = date('G', $end_date);
$first_day_hours = 24 - $shour;
$last_day_hours = $ehour;
$sdate = mktime(0,0,0,date('m',$start_date),date('d',$start_date)+1,date('Y',$start_date));
$edate = mktime(0,0,0,date('m',$end_date),date('d',$end_date)-1,date('Y',$end_date));
// initialize counters
$surge = 0;
$normal = 0;
if (in_array(date('N',$start_date), array(5,6,7))) {
$surge += $first_day_hours;
} else {
$normal += $first_day_hours;
}
if (in_array(date('N',$end_date), array(5,6,7))) {
$surge += $last_day_hours;
} else {
$normal += $last_day_hours;
}
while ($sdate<=$edate) {
if (in_array(date('N',$sdate), array(5,6,7))) {
$surge += 24;
} else {
$normal += 24;
}
$sdate = mktime(0,0,0,date('m',$sdate),date('d',$sdate)+1,date('Y',$sdate));
}
echo 'Normal: '.$normal.PHP_EOL;
echo ' Surge: '.$surge.PHP_EOL;
是你的計算一個星期的限制,也可以是長於一週/一個月/一年? – Wizard
它可以是任何東西@Wizard –
你有太複雜的解決方案,例如,你的$ start_day總會在循環內增加,如果它是6,你將在下一次迭代時有7。 – Wizard