Php add 5 working days to current date excluding weekends (sat-sun) and excluding (multiple) holidays

喜夏-厌秋 提交于 2019-12-04 14:54:49

问题


For delivery of our webshop, we need to calculate 5 working days from the current date in php.

Our working days are from monday to friday and we have several closing days (holidays) which cannot be included either.

I've found this script, but this doesn't include holidays.

<?php 

    $_POST['startdate'] = date("Y-m-d");
    $_POST['numberofdays'] = 5;

    $d = new DateTime( $_POST['startdate'] );
    $t = $d->getTimestamp();

    // loop for X days
    for($i=0; $i<$_POST['numberofdays']; $i++){

        // add 1 day to timestamp
        $addDay = 86400;

        // get what day it is next day
        $nextDay = date('w', ($t+$addDay));

        // if it's Saturday or Sunday get $i-1
        if($nextDay == 0 || $nextDay == 6) {
            $i--;
        }

        // modify timestamp, add 1 day
        $t = $t+$addDay;
    }

    $d->setTimestamp($t);

    echo $d->format('Y-m-d'). "\n";

?>

回答1:


You can use the "while statement", looping until get enough 5 days. Each time looping get & check one next day is in the holiday list or not.

Here is the the example:

$holidayDates = array(
    '2016-03-26',
    '2016-03-27',
    '2016-03-28',
    '2016-03-29',
    '2016-04-05',
);

$count5WD = 0;
$temp = strtotime("2016-03-25 00:00:00"); //example as today is 2016-03-25
while($count5WD<5){
    $next1WD = strtotime('+1 weekday', $temp);
    $next1WDDate = date('Y-m-d', $next1WD);
    if(!in_array($next1WDDate, $holidayDates)){
        $count5WD++;
    }
    $temp = $next1WD;
}

$next5WD = date("Y-m-d", $temp);

echo $next5WD; //if today is 2016-03-25 then it will return 2016-04-06 as many days between are holidays



回答2:


A function based on Tinh Dang's answer:

function getFutureBusinessDay($num_business_days, $today_ymd = null, $holiday_dates_ymd = []) {
    $num_business_days = min($num_business_days, 1000);
    $business_day_count = 0;
    $current_timestamp = empty($today_ymd) ? time() : strtotime($today_ymd);
    while ($business_day_count < $num_business_days) {
        $next1WD = strtotime('+1 weekday', $current_timestamp);
        $next1WDDate = date('Y-m-d', $next1WD);        
        if (!in_array($next1WDDate, $holiday_dates_ymd)) {
            $business_day_count++;
        }
        $current_timestamp = $next1WD;
    }
    return date('Y-m-d', $current_timestamp);
}

I made it limit the loop to 1000 business days. There could be no limit if desired.



来源:https://stackoverflow.com/questions/36196606/php-add-5-working-days-to-current-date-excluding-weekends-sat-sun-and-excludin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!