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

时间:2020-01-09 05:18:28

标签: php yii2

首先,在你们中的一些人可能将这个问题变成重复的问题之前。我经历了很多与我的问题有关的问题。但是,这些问题似乎无法解决我的问题。我想查找2个日期之间的天,周末和节假日除外。我所经历的问题在数组中声明#include <iostream> using namespace std; void room2(); void room1(); void room(void a); void room1() { cout << "next room" << endl; } void room2() { cout << "other rooom" << endl; } void room(void a) { cout << "Things happen here now you go to the next room" << endl; a(); } int main() { room(nextRoom()); } 的变量,并在该数组中初始化值。

下面是我在$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(); 。有什么最好的方法吗?

1 个答案:

答案 0 :(得分:2)

使用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) {
    $allDates[] = [
        'date' => $date->format('Y-m-d'),
        'dayNo' => $date->format('N'),
    ];
}

//Initialized public holiday
 $holidays = HolidayModelName::find()
    ->select('date')
    ->where(['between', 'date', $start->format('Y-m-d'), $endDate])
    ->indexBy('date')
    ->column();

$workDay = 0;

foreach ($allDates as $value) {
    $isWeekOff = $value['dayNo'] == 6 || $value['dayNo'] == 7;

    if (!$isWeekOff && !isset($holidays[$value['date']])) {
        $workDay++;
    }
}

// Result : 20 Work Days