/**
* 计算工作日天数结束日期
* 作者:beyonder@163.com
* 吐槽一下,一开始低估了这个算法的复杂性,用了两天时间,真的不容易,写好的算法必须要沉一下心来理清逻辑才能写出来,虽然写得还不是很完美,但在这小佩服一下自己。
* startDate:开始日期
* days:天数
* holidays:法定节假日字符串
* workDays:调休上班日字符串
* return:到期日期(不含)
*/
function getWorkingEndDate($startDate,$days,$holidays,$workDays)
{
//开始日期
$startDate = strtotime($startDate);
$daysnum=0;
$num=0;
//法定节假日数组
$holiDays=explode(",",$holidays);
//调休工作日数组
$workDays=explode(",",$workDays);
//法定节假日
$holiday=0;
//周末
$weekday=0;
//调休工作日
$workday=0;
//循环daysnum
while(($daysnum)<intval($days)){
//临时日期
$tempdate=$startDate+$num*(60*60*24);
//周末天数
if(date("N", $tempdate) == 6 || date("N", $tempdate) == 7)
$weekday++;
//周末天数遇到法定节假日减去周末天数
if(in_array(date('Y-m-d',$tempdate),$holiDays)&&(date("N", $tempdate) == 6 || date("N", $tempdate) == 7))
$weekday--;
//法定节假日天数
if(in_array(date('Y-m-d',$tempdate),$holiDays))
$holiday++;
//法定调休工作日
if(in_array(date('Y-m-d',$tempdate),$workDays))
$workday++;
//循环自增
$num++;
//天数=循环天数+工作日-节假日-周末
$daysnum=$num+$workday-$holiday-$weekday;
}
//最后计算天数正好与之前计算相反
//天数=需要的工作日-法定调休工作日+法定节假日+周末天数
$daysnum=$days-$workday+$holiday+$weekday;
//返回
return date("Y-m-d H:i:s",$startDate+$daysnum*(60*60*24));
}
/**
* 计算两日期之间的工作日天数
* 作者:beyonder@163.com
* startDate:开始日期
* endDate:结束日期
* holidays:法定节假日
* workDays:调休上班日
*/
function getWorkingDays($startDate, $endDate, $holidays,$workDays)
{
$endDate = strtotime($endDate);
$startDate = strtotime($startDate);
$days = ($endDate - $startDate) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
} else {
if ($the_first_day_of_week == 7) {
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
$no_remaining_days--;
}
} else {
$no_remaining_days -= 2;
}
}
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0) {
$workingDays += $no_remaining_days;
}
//法定休息日计算
$holidays=explode(",",$holidays);
for($i=0;$i<count($holidays);$i++){
$time_stamp = strtotime($holidays[$i]);
if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N", $time_stamp) != 6 && date("N", $time_stamp) != 7)
$workingDays--;
}
//调休工作日调整
$workDays=explode(",",$workDays);
for($i=0;$i<count($workDays);$i++){
$time_stamp = strtotime($workDays[$i]);
if ($startDate <= $time_stamp && $time_stamp <= $endDate && (date("N", $time_stamp) == 6 || date("N", $time_stamp) == 7))
$workingDays++;
}
return $workingDays;
}