我试图使用
PHP获得接下来的3天,但如果日期是周末或定义的假期,我想跳过该日期.
例如,如果日期是2013年12月23日星期一
我的假日日期是阵列(‘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,$arr_date[1],$arr_date[2]+$counter,$arr_date[0])); if ($dayOfTheWeek == 6) { $counter += 2; } $date = date("Y-m-d",$arr_date[0])); echo $date; $counter++; }
我遇到的问题是我不知道如何排除假期日期.
解决方法
使用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):
$holidays = array('12-24' => '','12-25' => ''); $weekend = array('Sun' => '','Sat' => ''); $date = new DateTime('2013-12-23'); $nextDay = clone $date; $i = 0; $nextDates = array(); while ($i < 3) { $nextDay->add('P1D'); if (isset($holidays[$nextDay->format('m-d')])) continue; if (isset($weekend[$nextDay->format('D')])) continue; $nextDates[] = $nextDay->format('Y-m-d'); $i++; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。