Calculate business days

后端 未结 30 1818
猫巷女王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条回答
  •  既然无缘
    2020-11-22 06:13

    Here is a recursive solution. It can easily be modified to only keep track of and return the latest date.

    //  Returns a $numBusDays-sized array of all business dates, 
    //  starting from and including $currentDate. 
    //  Any date in $holidays will be skipped over.
    
    function getWorkingDays($currentDate, $numBusDays, $holidays = array(), 
      $resultDates = array())
    {
      //  exit when we have collected the required number of business days
      if ($numBusDays === 0) {
        return $resultDates;
      }
    
      //  add current date to return array, if not a weekend or holiday
      $date = date("w", strtotime($currentDate));
      if ( $date != 0  &&  $date != 6  &&  !in_array($currentDate, $holidays) ) {
        $resultDates[] = $currentDate;
        $numBusDays -= 1;
      }
    
      //  set up the next date to test
      $currentDate = new DateTime("$currentDate + 1 day");
      $currentDate = $currentDate->format('Y-m-d');
    
      return getWorkingDays($currentDate, $numBusDays, $holidays, $resultDates);
    }
    
    //  test
    $days = getWorkingDays('2008-12-05', 4);
    print_r($days);
    

提交回复
热议问题