php – 获得3个下一个工作日期,跳过周末和假期

我试图使用 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++;
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...