Calculate business days

后端 未结 30 2133
猫巷女王i
猫巷女王i 2020-11-22 05:16

I need a method for adding \"business days\" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10.

At a minimum I need the code to understand weekend

30条回答
  •  Happy的楠姐
    2020-11-22 06:00

    calculate workdays between two dates including holidays and custom workweek

    The answer is not that trivial - thus my suggestion would be to use a class where you can configure more than relying on simplistic function (or assuming a fixed locale and culture). To get the date after a certain number of workdays you'll:

    1. need to specify what weekdays you'll be working (default to MON-FRI) - the class allows you to enable or disable each weekday individually.
    2. need to know that you need to consider public holidays (country and state) to be accurate
      • e.g. https://github.com/khatfield/php-HolidayLibrary/blob/master/Holidays.class.php
      • or hardcode the data: e.g. from http://www.feiertagskalender.ch/?hl=en
      • or pay for data-API http://www.timeanddate.com/services/api/holiday-api.html

    Functional Approach

    /**
     * @param days, int
     * @param $format, string: dateformat (if format defined OTHERWISE int: timestamp) 
     * @param start, int: timestamp (mktime) default: time() //now
     * @param $wk, bit[]: flags for each workday (0=SUN, 6=SAT) 1=workday, 0=day off
     * @param $holiday, string[]: list of dates, YYYY-MM-DD, MM-DD 
     */
    function working_days($days, $format='', $start=null, $week=[0,1,1,1,1,1,0], $holiday=[])
    {
        if(is_null($start)) $start = time();
        if($days <= 0) return $start;
        if(count($week) != 7) trigger_error('workweek must contain bit-flags for 7 days');
        if(array_sum($week) == 0) trigger_error('workweek must contain at least one workday');
        $wd = date('w', $start);//0=sun, 6=sat
        $time = $start;
        while($days)
        {
            if(
            $week[$wd]
            && !in_array(date('Y-m-d', $time), $holiday)
            && !in_array(date('m-d', $time), $holiday)
            ) --$days; //decrement on workdays
            $wd = date('w', $time += 86400); //add one day in seconds
        }
        $time -= 86400;//include today
        return $format ? date($format, $time): $time;
    }
    
    //simple usage
    $ten_days = working_days(10, 'D F d Y');
    echo '
    ten workingdays (MON-FRI) disregarding holidays: ',$ten_days; //work on saturdays and add new years day as holiday $ten_days = working_days(10, 'D F d Y', null, [0,1,1,1,1,1,1], ['01-01']); echo '
    ten workingdays (MON-SAT) disregarding holidays: ',$ten_days;

提交回复
热议问题