我正在尝试使用php获得接下来的3天,但如果日期是周末或定义的假期,我想跳过该日期。
例如,如果日期是2013年12月23日星期一
我的假期是array('2013-12-24', '2013-12-25');
该脚本将返回
Monday, December 23, 2013
Thursday, December 26, 2013
Friday, December 27, 2013
Monday, December 30, 2013
她是我现在的代码:
$arr_date = explode('-', '2013-12-23');
$counter = 0;
for ($iLoop = 0; $iLoop < 4; $iLoop++)
{
$dayOfTheWeek = date("N", mktime(0, 0, 0, $arr_date[1], $arr_date[2]+$counter, $arr_date[0]));
if ($dayOfTheWeek == 6) { $counter += 2; }
$date = date("Y-m-d", mktime(0, 0, 0, $arr_date[1], $arr_date[2]+$counter, $arr_date[0]));
echo $date;
$counter++;
}
我遇到的问题是我不知道如何排除假期日期。
答案 0 :(得分:4)
使用DateTime
在接下来的日子里进行递归并进行字符串比较检查以查看下一个生成的日期是否属于使用in_array
的假日或周末数组
$holidays = array('12-24', '12-25');
$weekend = array('Sun','Sat');
$date = new DateTime('2013-12-23');
$nextDay = clone $date;
$i = 0; // We have 0 future dates to start with
$nextDates = array(); // Empty array to hold the next 3 dates
while ($i < 3)
{
$nextDay->add('P1D'); // Add 1 day
if (in_array($nextDay->format('m-d'), $holidays)) continue; // Don't include year to ensure the check is year independent
// Note that you may need to do more complicated things for special holidays that don't use specific dates like "the last Friday of this month"
if (in_array($nextDay->format('D'), $weekend)) continue;
// These next lines will only execute if continue isn't called for this iteration
$nextDates[] = $nextDay->format('Y-m-d');
$i++;
}
使用isset()
的建议代替O(1)
:
O(n)
答案 1 :(得分:3)
Here is a simple example如何获得两个日期之间的工作日数;您只需修改以满足您的需求:
function number_of_working_dates($from, $days) {
$workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)
$holidayDays = ['*-12-25', '*-01-01', '2013-12-24', '2013-12-25']; # variable and fixed holidays
$from = new DateTime($from);
$dates = [];
$dates[] = $from->format('Y-m-d');
while ($days) {
$from->modify('+1 day');
if (!in_array($from->format('N'), $workingDays)) continue;
if (in_array($from->format('Y-m-d'), $holidayDays)) continue;
if (in_array($from->format('*-m-d'), $holidayDays)) continue;
$dates[] = $from->format('Y-m-d');
$days--;
}
return $dates;
}
print_r( number_of_working_dates('2013-12-23', 3) );