基于工作日计算日期的PHP函数

4
我正在使用这个函数(我在论坛上找到的)来计算日期范围内的工作日数量:
<?php
//The function returns the no. of business days between two dates and it skips the holidays
function getWorkingDays($startDate,$endDate,$holidays){
// do strtotime calculations just once
$endDate = strtotime($endDate);
$startDate = strtotime($startDate);


//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 1;

$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);

//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);

//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week) {
    if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
    if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
    // (edit by Tokes to fix an edge case where the start day was a Sunday
    // and the end day was NOT a Saturday)

    // the day of the week for start is later than the day of the week for end
    if ($the_first_day_of_week == 7) {
        // if the start date is a Sunday, then we definitely subtract 1 day
        $no_remaining_days--;

        if ($the_last_day_of_week == 6) {
            // if the end date is a Saturday, then we subtract another day
            $no_remaining_days--;
        }
    }
    else {
        // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
        // so we skip an entire weekend and subtract 2 days
        $no_remaining_days -= 2;
    }
}

//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
  $workingDays += $no_remaining_days;
}

//We subtract the holidays
foreach($holidays as $holiday){
    $time_stamp=strtotime($holiday);
    //If the holiday doesn't fall in weekend
    if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
        $workingDays--;
}

return $workingDays;
}

//Example:

$holidays=array("2008-12-25","2008-12-26","2009-01-01");

echo getWorkingDays("$startdate","$enddate",$holidays)
?>

现在我想扩展这个函数。如果我从开始日期增加X个工作日,我想生成将是哪一天。例如,假设我有一个变量保存了值20.
$workingdays = "20";

如果 $startdate2012-06-01, 我希望这个函数能够计算出开始日期加上 20 个工作日后的日期为 2012-06-28。这种情况是否可能?


这看起来是一个学习TDD的完美例子 :) - Nico Haase
6个回答

11

我之前使用下面的函数实现了类似的功能。关键在于跳过周末,你可以进一步将其扩展为跳过节假日。

示例:

调用函数 - > addDays(strtotime($startDate), 20, $skipdays,$skipdates = array())

 <?php
    function addDays($timestamp, $days, $skipdays = array("Saturday", "Sunday"), $skipdates = NULL) {
        // $skipdays: array (Monday-Sunday) eg. array("Saturday","Sunday")
        // $skipdates: array (YYYY-mm-dd) eg. array("2012-05-02","2015-08-01");
       //timestamp is strtotime of ur $startDate
        $i = 1;

        while ($days >= $i) {
            $timestamp = strtotime("+1 day", $timestamp);
            if ( (in_array(date("l", $timestamp), $skipdays)) || (in_array(date("Y-m-d", $timestamp), $skipdates)) )
            {
                $days++;
            }
            $i++;
        }

        return $timestamp;
        //return date("m/d/Y",$timestamp);
    }
    ?>

[编辑]:刚刚阅读了一篇非常棒的文章,希望这可以帮到你 http://net.tutsplus.com/tutorials/php/dates-and-time-the-oop-way/


你能否详细解释一下如何使用它?我对PHP函数非常陌生。 - David
调用函数 -> addDays(strtotime($startDate), 20, $skipdays,$skipdates = NULL); 如果您发送$skipDays和$skipDates的空值也可以,这种情况下默认将跳过周六、周日和没有额外日期。 - Eswar Rajesh Pinapala
我该如何将那个时间戳转换为实际的年-月-日日期?是的,我是新手。 - David
$startdate 变量似乎存在一些问题。如果我手动使用 strtotime(2012-06-01),它可以工作,但是 strtotime($startdate) 不行。即使我使用 echo $startdate; 输出正确的日期... - David
三个问题:
  1. 你遇到了Juggling问题吗?
  2. 你能做一个快速测试,进行类型转换吗?
  3. 执行以下代码: $startDate = (string)$startDate; echo strtotime($startDate);
- Eswar Rajesh Pinapala
谢谢,我会使用这个代码,但是请返回$days,这样我就知道实际上不包括周末的天数了。 - SigmaSteve

3
如果有人感兴趣,我正在使用这个函数将X个工作日添加到日期中。该函数接受一个时间戳并返回一个时间戳。可以通过数组指定节假日(如果在美国,可以使用usBankHolidays())。
目前,它假设周六和周日不是工作日,但很容易改变。 代码:
function addBusinessDays($date, $days, $holidays = array()) {
    $output = new DateTime();
    $output->setTimestamp($date);
    while ($days > 0) {
        $weekDay = $output->format('N');

        // Skip Saturday and Sunday
        if ($weekDay == 6 || $weekDay == 7) {
            $output = $output->add(new DateInterval('P1D'));
            continue;
        }

        // Skip holidays
        $strDate = $output->format('Y-m-d');
        foreach ($holidays as $s) {
            if ($s == $strDate) {
                $output = $output->add(new DateInterval('P1D'));
                continue 2;
            }
        }

        $days--;
        $output = $output->add(new DateInterval('P1D'));
    }
    return $output->getTimestamp();
}

function usBankHolidays($format = 'datesonly') {
    $output = array(
        array('2015-05-25', 'Memorial Day'),
        array('2015-07-03', 'Independence Day'),
        array('2015-09-07', 'Labor Day'),
        array('2015-10-12', 'Columbus Day'),
        array('2015-11-11', 'Veterans Day'),
        array('2015-11-26', 'Thanksgiving Day'),
        array('2015-12-25', 'Christmas Day'),
        array('2016-01-01', 'New Year Day'),
        array('2016-01-18', 'Martin Luther King Jr. Day'),
        array('2016-02-15', 'Presidents Day (Washingtons Birthday)'),
        array('2016-05-30', 'Memorial Day'),
        array('2016-07-04', 'Independence Day'),
        array('2016-09-05', 'Labor Day'),
        array('2016-10-10', 'Columbus Day'),
        array('2016-11-11', 'Veterans Day'),
        array('2016-11-24', 'Thanksgiving Day'),
        array('2016-12-25', 'Christmas Day'),
        array('2017-01-02', 'New Year Day'),
        array('2017-01-16', 'Martin Luther King Jr. Day'),
        array('2017-02-20', 'Presidents Day (Washingtons Birthday)'),
        array('2017-05-29', 'Memorial Day'),
        array('2017-07-04', 'Independence Day'),
        array('2017-09-04', 'Labor Day'),
        array('2017-10-09', 'Columbus Day'),
        array('2017-11-10', 'Veterans Day'),
        array('2017-11-23', 'Thanksgiving Day'),
        array('2017-12-25', 'Christmas Day'),
        array('2018-01-01', 'New Year Day'),
        array('2018-01-15', 'Martin Luther King Jr. Day'),
        array('2018-02-19', 'Presidents Day (Washingtons Birthday)'),
        array('2018-05-28', 'Memorial Day'),
        array('2018-07-04', 'Independence Day'),
        array('2018-09-03', 'Labor Day'),
        array('2018-10-08', 'Columbus Day'),
        array('2018-11-12', 'Veterans Day'),
        array('2018-11-22', 'Thanksgiving Day'),
        array('2018-12-25', 'Christmas Day'),
        array('2019-01-01', 'New Year Day'),
        array('2019-01-21', 'Martin Luther King Jr. Day'),
        array('2019-02-18', 'Presidents Day (Washingtons Birthday)'),
        array('2019-05-27', 'Memorial Day'),
        array('2019-07-04', 'Independence Day'),
        array('2019-09-02', 'Labor Day'),
        array('2019-10-14', 'Columbus Day'),
        array('2019-11-11', 'Veterans Day'),
        array('2019-11-28', 'Thanksgiving Day'),
        array('2019-12-25', 'Christmas Day'),
        array('2020-01-01', 'New Year Day'),
        array('2020-01-20', 'Martin Luther King Jr. Day'),
        array('2020-02-17', 'Presidents Day (Washingtons Birthday)'),
        array('2020-05-25', 'Memorial Day'),
        array('2020-07-03', 'Independence Day'),
        array('2020-09-07', 'Labor Day'),
        array('2020-10-12', 'Columbus Day'),
        array('2020-11-11', 'Veterans Day'),
        array('2020-11-26', 'Thanksgiving Day'),
        array('2020-12-25', 'Christmas Day '),
    );

    if ($format == 'datesonly') {
        $temp = array();
        foreach ($output as $item) {
            $temp[] = $item[0];
        }
        $output = $temp;
    }

    return $output;
}

用法:

$deliveryDate = addBusinessDays(time(), 7, usBankHolidays());

尝试使所有假期都是动态的 :) - LucScu
1
在foreach $holidays中有一个bug。continue语句在foreach范围内而不是while范围内,你必须使用continue 2。 - LucScu
你好,我很喜欢你的算法,并且进行了一些小修改后使用了它。非常感谢你,你也是。 - LucScu

1

从@this.lau_的回答中,重写了一个更简单、更合理的算法,并添加了动态(固定)假期。

public function addBusinessDays($date, $days) {

    $output = new DateTime();
    $output->setTimestamp($date);

    while ($days > 0) {

        $output = $output->add(new DateInterval('P1D'));
        $weekDay = $output->format('N');
        $strDate = $output->format('Y-m-d');

        // Skip Saturday and Sunday
        if ($weekDay == 6 || $weekDay == 7) {

            continue;

        }

        // Skip holidays
        $holidays = $this->_getHolidays();            

        foreach ($holidays as $holiday_date => $holiday_name) {

            if ($holiday_date == $strDate) {

                continue 2;

            }

        }

        $days--;

    }

    return $output->getTimestamp();

}



public function _getHolidays() {

    $feste = array(
        date("Y") . "-01-01" => "Capodanno", 
        date("Y") . "-01-06" => "Epifania", 
        date("Y") . "-04-25" => "Liberazione", 
        date("Y") . "-05-01" => "Festa Lavoratori", 
        date("Y") . "-06-02" => "Festa della Repubblica", 
        date("Y") . "-08-15" => "Ferragosto", 
        date("Y") . "-11-01" => "Tutti Santi", 
        date("Y") . "-12-08" => "Immacolata", 
        date("Y") . "-12-25" => "Natale", 
        date("Y") . "-12-26" => "St. Stefano"
    );

    return $feste;

}

调用带有以下参数的函数:
$deliveryDate = addBusinessDays(time(), 7);

0

使用this.lau_ function,我能够反转它,用于减去日期,用作过期日期。希望这能帮助到某人:

function subBusinessDays( $date, $days, $holidays = array() ) {
            $output = new DateTime();
            $output->setTimestamp( $date );

            while ( $days > 0 ) {

                $output = $output->sub( new DateInterval( 'P1D' ) );

                // Skip holidays
                $strDate = $output->format( 'Y-m-d' );
                if ( in_array( $strDate, $holidays ) ) {
                    // Skip Saturday and Sunday
                    $output = $output->sub( new DateInterval( 'P1D' ) );
                    continue;
                }

                $weekDay = $output->format( 'N' );
                if ($weekDay <= 5 ) {
                    $days --;
                }

            }

            return $output->getTimestamp();
        }

0

我有一个更好的解决方案,只需要在函数中使用两个参数。

只需调用该函数即可。

addDays($currentdate, $WordkingDatestoadd);

然后,使用以下函数

function addDays($timestamp, $days) {

$workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)
$holidayDays = ['*-12-25', '*-01-01']; # variable and fixed holidays

$timestamp = new DateTime($timestamp);
$days = $days;

for($i=1 ; $i <= $days; $i++){
    $timestamp = $timestamp->modify('+1 day');
    if ((!in_array($timestamp->format('N'), $workingDays)) && (!in_array($timestamp->format('*-m-d'), $holidayDays))){
        $i--;
    }
}

$timestamp = $timestamp->format('Y-m-d');
return $timestamp;
}

0

在这里,我使用HolidayAPI动态获取假期列表。HolidayAPI是免费实现的。我是孟加拉国人,所以我使用国家代码BD。 API链接 - https://holidayapi.com/v1/holidays?pretty&key=your_key&country=your_country_code&year=2020

// cURL start
$cURLConnection = curl_init();
curl_setopt($cURLConnection, CURLOPT_URL, 'your api');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$phoneList = curl_exec($cURLConnection);
curl_close($cURLConnection);
$dateResponse = json_decode($phoneList);
// cURL end

$holidays = array(); //declear holidays array`enter code here`
for ($i=0;$i<count($dateResponse->holidays);$i++){
    $holidays[] = $dateResponse->holidays[$i]->date;  //inserting holidays in array from api
}

$startDate = "2020-02-26";  //insert value thats you prefer
$timestamp  = strtotime($startDate);  // convert date to time
$weekends = array("Friday", "Saturday");
$days = 0;  //initialization days counter

while (1){  //
    $timestamp = strtotime("+1 day", $timestamp); //day increment
    if ( (in_array(date("l", $timestamp), $weekends)) || (in_array(date("Y-m-d", $timestamp), $holidays)) ) //checking weekends and holidays
    {
        continue;
    }else{
        $days++;``
        if($days >= 5){  //interval - What will be the working days after 5 days
            echo date("Y-m-d", $timestamp); // print expected output
            break;
        }
    }
}

输入:2020-02-26 输出:2020-03-05


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接