phpdate

Next business day of given date in PHP


Does anyone have a PHP snippet to calculate the next business day for a given date? How does, for example, YYYY-MM-DD need to be converted to find out the next business day?

Example: For 03.04.2011 (DD-MM-YYYY) the next business day is 04.04.2011. For 08.04.2011 the next business day is 11.04.2011.

This is the variable containing the date I need to know the next business day for

$cubeTime['time'];

Variable contains: 2011-04-01 result of the snippet should be: 2011-04-04


Solution

  • Next Weekday

    This finds the next weekday from a specific date (not including Saturday or Sunday):

    echo date('Y-m-d', strtotime('2011-04-05 +1 Weekday'));
    

    You could also do it with a date variable of course:

    $myDate = '2011-04-05';
    echo date('Y-m-d', strtotime($myDate . ' +1 Weekday'));
    

    UPDATE: Or, if you have access to PHP's DateTime class (very likely):

    $date = new DateTime('2018-01-27');
    $date->modify('+7 weekday');
    echo $date->format('Y-m-d');
    

    Want to Skip Holidays?:

    Although the original poster mentioned "I don't need to consider holidays", if you DO happen to want to ignore holidays, just remember - "Holidays" is just an array of whatever dates you don't want to include and differs by country, region, company, person...etc.

    Simply put the above code into a function that excludes/loops past the dates you don't want included. Something like this:

    $tmpDate = '2015-06-22';
    $holidays = ['2015-07-04', '2015-10-31', '2015-12-25'];
    $i = 1;
    $nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
    
    while (in_array($nextBusinessDay, $holidays)) {
        $i++;
        $nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
    }
    

    I'm sure the above code can be simplified or shortened if you want. I tried to write it in an easy-to-understand way.