Calculate business days

后端 未结 30 1831
猫巷女王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:04

    Here is another solution without for loop for each day.

    $from = new DateTime($first_date);
    $to = new DateTime($second_date);
    
    $to->modify('+1 day');
    $interval = $from->diff($to);
    $days = $interval->format('%a');
    
    $extra_days = fmod($days, 7);
    $workdays = ( ( $days - $extra_days ) / 7 ) * 5;
    
    $first_day = date('N', strtotime($first_date));
    $last_day = date('N', strtotime("1 day", strtotime($second_date)));
    $extra = 0;
    if($first_day > $last_day) {
       if($first_day == 7) {
           $first_day = 6;
       }
    
       $extra = (6 - $first_day) + ($last_day - 1);
       if($extra < 0) {
           $extra = $extra * -1;
       }
    }
    if($last_day > $first_day) {
        $extra = $last_day - $first_day;
    }
    $days = $workdays + $extra
    

提交回复
热议问题