代码之家  ›  专栏  ›  技术社区  ›  Jonathan

计算两个日期之间没有公共假日的工作日

php
  •  0
  • Jonathan  · 技术社区  · 11 年前

    我有以下代码计算工作日总数:(工作日)

    <?php
    //get current month for example
    if(!isset($_GET['from'])) {
        $beginday=date("Y-m-01");
    } else {
        $beginday=date($_GET['from']);
    }
    if(!isset($_GET['to'])) {
        $lastday=date("Y-m-01");
    } else {
        $lastday=date($_GET['to']);
    }
    
    $nr_work_days = getWorkingDays($beginday,$lastday);
    echo $nr_work_days;
    
    function getWorkingDays($startDate, $endDate){
     $begin=strtotime($startDate);
     $end=strtotime($endDate);
     if($begin>$end){
      echo "startdate is in the future! <br />";
      return 0;
     }else{
       $no_days=0;
       $weekends=0;
      while($begin<=$end){
        $no_days++; // no of days in the given interval
        $what_day=date("N",$begin);
         if($what_day>5) { // 6 and 7 are weekend days
              $weekends++;
         };
        $begin+=86400; // +1 day
      };
      $working_days=$no_days-$weekends;
      return $working_days;
     }
    }
    ?>
    

    我现在怀念的是一个将所有公共假期都删掉的功能。有什么建议吗?最好的方法是什么?

    1 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    您可以使用,

    //Subtract the holidays
    foreach($holidays as $holiday){
        $time_stamp=strtotime($holiday);
        //If the holiday doesn't fall in weekend
        if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
            $working_days--;
    }
    

    注: $holidays 是您所有假日日期的数组。

    参考 : Calculate business days

    推荐文章