yii2 如何计算日期之间的天数,不包括周末和节假日

好的,首先,在你们中的一些人可能把这个问题变成一个重复的问题之前。我经历了许多与我的问题相关的问题。但似乎这些问题无法解决我的问题。我想查找 2 个日期之间的天数,不包括周末和节假日。我经历过的问题声明了数组中的变量$holiday并初始化该数组中的值。


以下是我的代码,LeaveapplicationController.php用于查找不包括周末的日期


$date1 = $model->startDate;

        $date2 = $model->endDate;


        $date1 = strtotime($date1);

        $date2 = strtotime($date2);



        //Initialized public holiday

        $holidays = array("2020-01-21", "2020-01-22", "2020-01-23");


        $days = ($date2 - $date1)/86400 + 1;


        $fullWeek = floor($days/7);

        $remainDay = fmod($days,7);


        $firstDay = date("N", $date1);

        $lastDay = date("N", $date2);


        if($firstDay <= $lastDay){

            if($firstDay <= 6 && 6 <= $lastDay) $remainDay--;

            if($firstDay <= 7 && 7 <= $lastDay) $remainDay--;

        }

        else 

        {

            if($firstDay == 7){

                $remainDay--;


                if($lastDay == 6){

                    $remainDay--;

                }

            }

            else{

                $remainDay -= 2;

            }

        }

        $workDay = $fullWeek * 5;

        if($remainDay > 0)

        {

            $workDay += $remainDay;

        }

        foreach($holidays as $holiday){

            $timeStamp = strtotime($holiday);

            if($date1 <= $timeStamp && $timeStamp <= $date2 && date("N", $timeStamp) != 6 && date("N", $timeStamp) != 7)

            $workDay--;

        }

        $model->no_of_days=$workDay;

        $model->save();

所以,我尝试过使用一些值初始化的假期。就我而言,我想$holiday=array()用另一个数据库表中的数据替换它。有没有最好的方法呢?


斯蒂芬大帝
浏览 173回答 1
1回答

繁星淼淼

使用DateTime$start = new \DateTime($model->startDate); //2020-01-01$end = new \DateTime($model->endDate); //2020-01-31$endDate = $end->format('Y-m-d');$interval = new \DateInterval('P1D');$end->add($interval);$period = new \DatePeriod($start, $interval, $end);foreach ($period as $date) {&nbsp; &nbsp; $allDates[] = [&nbsp; &nbsp; &nbsp; &nbsp; 'date' => $date->format('Y-m-d'),&nbsp; &nbsp; &nbsp; &nbsp; 'dayNo' => $date->format('N'),&nbsp; &nbsp; ];}//Initialized public holiday&nbsp;$holidays = HolidayModelName::find()&nbsp; &nbsp; ->select('date')&nbsp; &nbsp; ->where(['between', 'date', $start->format('Y-m-d'), $endDate])&nbsp; &nbsp; ->indexBy('date')&nbsp; &nbsp; ->column();$workDay = 0;foreach ($allDates as $value) {&nbsp; &nbsp; $isWeekOff = $value['dayNo'] == 6 || $value['dayNo'] == 7;&nbsp; &nbsp; if (!$isWeekOff && !isset($holidays[$value['date']])) {&nbsp; &nbsp; &nbsp; &nbsp; $workDay++;&nbsp; &nbsp; }}// Result : 20 Work Days
打开App,查看更多内容
随时随地看视频慕课网APP