Calculate business days

后端 未结 30 2259
猫巷女王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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:52

    function get_business_days_forward_from_date($num_days, $start_date='', $rtn_fmt='Y-m-d') {

    // $start_date will default to today    
    
    if ($start_date=='') { $start_date = date("Y-m-d"); }
    
    $business_day_ct = 0;
    
    $max_days = 10000 + $num_days;  // to avoid any possibility of an infinite loop
    
    
    // define holidays, this currently only goes to 2012 because, well, you know... ;-)
    // if the world is still here after that, you can find more at
    // http://www.opm.gov/Operating_Status_Schedules/fedhol/2013.asp
    // always add holidays in order, because the iteration will stop when the holiday is > date being tested
    
    $fed_holidays=array(
        "2010-01-01",
        "2010-01-18",
        "2010-02-15",
        "2010-05-31",
        "2010-07-05",
        "2010-09-06",
        "2010-10-11",
        "2010-11-11",
        "2010-11-25",
        "2010-12-24",
    
        "2010-12-31",
        "2011-01-17",
        "2011-02-21",
        "2011-05-30",
        "2011-07-04",
        "2011-09-05",
        "2011-10-10",
        "2011-11-11",
        "2011-11-24",
        "2011-12-26",
    
        "2012-01-02",
        "2012-01-16",
        "2012-02-20",
        "2012-05-28",
        "2012-07-04",
        "2012-09-03",
        "2012-10-08",
        "2012-11-12",
        "2012-11-22",
        "2012-12-25",
        );
    
    $curr_date_ymd = date('Y-m-d', strtotime($start_date));    
    
    for ($x=1;$x<$max_days;$x++)
    {
        if (intval($num_days)==intval($business_day_ct)) { return(date($rtn_fmt, strtotime($curr_date_ymd))); }  // date found - return
    
        // get next day to check
    
        $curr_date_ymd = date('Y-m-d', (strtotime($start_date)+($x * 86400)));   // add 1 day to the current date
    
        $is_business_day = 1;
    
        // check if this is a weekend   1 (for Monday) through 7 (for Sunday)
    
        if ( intval(date("N",strtotime($curr_date_ymd))) > 5) { $is_business_day = 0; }
    
        //check for holiday
        foreach($fed_holidays as $holiday)
        {
            if (strtotime($holiday)==strtotime($curr_date_ymd))  // holiday found
            {
                $is_business_day = 0;
                break 1;
            }
    
            if (strtotime($holiday)>strtotime($curr_date_ymd)) { break 1; }  // past date, stop searching (always add holidays in order)
    
    
        }
    
        $business_day_ct = $business_day_ct + $is_business_day;  // increment if this is a business day
    
    } 
    
    // if we get here, you are hosed
    return ("ERROR");
    

    }

提交回复
热议问题