需求
- 维护一个假期表
- 以当前时间为参数获取下一交易日,当前时间格式为(yyyy-mm-dd)
实现参考
https://www.optbbs.com/thread-4460970-1-1.html
递归实现
$holidaysList=['2020-05-01','2020-05-02','2020-05-03','2020-05-04','2020-05-05','2020-05-06'];//数据库维护一个记录所有假期的表,这里简化为一个数组;
/**
核心代码
*/
function getDueDayAfterHoliday(string $nextDay,$holidayList){
foreach($holidayList as $d){
if($nextDay==$d){
$nextDay=getDueAfterHoliday(date(yyyy-mm-dd,strtotime('+1day',strtotime($nextDay))),$holidayList);
}
}
$nextDay=getExceptWeekendDay($nextDay);
return $nextDay;
}
/**
去除星期六、星期天
*/
function getExceptWeekendDay(string $day){
if(date('w',strtotime($day))===6){
$nextDay=date('yyyy-mm-dd',strotime('+2 day',strtotime($day)));
}else if(date('w',strtotime($day))===0){
$nextDay=date('yyyy-mm-dd',strotime('+1 day',strtotime($day)));
}
return $nextDay
}
非递归实现(更好的实现)
function getDueDayAfterHoliday(string $nextDay,int $days){
$days=abs($days);
if($days===0){
return $nextDay;
}else{
while($days>0){
$endDay=date('yyyy-mm-dd',strotime("+ {$days}day",strtotime($nextDay)));
$days=getHolidaysTotal($nextDay,$endDay);
$nextDay=$endDay;
}
return $nextDay;
}
}
/**
通过比较获取两日期之间假期天数
*/
function getHolidaysTotal(string $nextDay,int $endDay){
if($a=strtotime($nextDay)-$b=strtotime($endDay)<0){
$days=round(($b-$a)/3600/24);
}else{
$days=round(($a-$b)/3600/24);
}
return $days
}