使用 PHP 跳过周末根据开始日期和值计算日期


Calculate what the date will be based on startdate and value using PHP skip weekends

我有一个开始日期,假设这是$startDate = 2012-08-01;,我有一个存储 INT 值的变量,假设这是$value = 10;

我想计算从开始日期 + 10 天并跳过周末的日期。

使用上述值,结果将是2012-08-15

这将如何完成?

这远非高效,但是当它可读时,谁会在乎呢? :)

<?php
function calculateNextDate($startDate, $days)
{
        $dateTime = new DateTime($startDate);
        while($days) {
            $dateTime->add(new DateInterval('P1D'));    
            if ($dateTime->format('N') < 6) {
                $days--;
            }
        }
        return $dateTime->format('Y-m-d');
}
echo calculateNextDate('2012-08-01', 10); // return 2012-08-15

演示

发生的事情应该很容易遵循。首先,我们使用用户提供的日期创建一个新的DateTime对象。之后,我们将循环浏览要添加到日期的天数。当我们在周末达到某一天时,我们不会从我们想要添加到日期的日子中减去一天。

你可以使用 PHP 的 strtotime 函数来 + n 天/小时等,

对于不包括周末,请查看此处:32小时前 不包括周末与PHP

试试这个

<?php
function businessdays($begin, $end) {
    $rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
    $rend = is_string($end) ? strtotime(strval($end)) : $end;
    if ($rbegin < 0 || $rend < 0)
        return 0;
    $begin = workday($rbegin, TRUE);
    $end = workday($rend, FALSE);
    if ($end < $begin) {
        $end = $begin;
        $begin = $end;
    }
    $difftime = $end - $begin;
    $diffdays = floor($difftime / (24 * 60 * 60)) + 1;
    if ($diffdays < 7) {
        $abegin = getdate($rbegin);
        $aend = getdate($rend);
        if ($diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
            return 0;
        $abegin = getdate($begin);
        $aend = getdate($end);
        $weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
    } else
        $weekends = floor($diffdays / 7);
    return $diffdays - ($weekends * 2);
}
function workday($date, $begindate = TRUE) {
    $adate = getdate($date);
    $day = 24 * 60 * 60;
    if ($adate['wday'] == 0) // Sunday
        $date += $begindate ? $day : -($day * 2);
    return $date;
}
$def_date="";//define your date here
$addDay='5 days';//no of previous days  
date_add($date, date_interval_create_from_date_string($addDay));
echo businessdays($date, $def_date); //date prior to another date 
?>

修改自 PHP.net

如果您只想添加一个日期 +10,您可能需要考虑以下因素:

日期("Y-m-d", strtotime("+10 days"));