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()替换为另一个数据库表中的数据。有什么最好的方法吗?

使用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

相关内容

  • 没有找到相关文章