无周末的日差

2022-08-30 13:47:59

我想计算与用户输入的总天差

例如,当用户输入

start_date = 2012-09-06end-date = 2012-09-11

现在,我正在使用此代码来查找差异

$count = abs(strtotime($start_date) - strtotime($end_date));
$day   = $count+86400;
$total = floor($day/(60*60*24));

结果总数为 6。但问题是我不想包括周末(周六和周日)的日子。

2012-09-06
2012-09-07
2012-09-08 Saturday
2012-09-09 Sunday
2012-09-10
2012-09-11

所以结果将是4

----更新---

我有一个包含日期的表,表名是假日日期

例如,该表包含2012-09-07

因此,总天数将为 3,因为它未计算假日日期

我如何做到这一点来将输入的日期等同于表中的日期?


答案 1

使用我的最爱非常容易:DateTimeDateIntervalDatePeriod

$start = new DateTime('2012-09-06');
$end = new DateTime('2012-09-11');
// otherwise the  end date is excluded (bug?)
$end->modify('+1 day');

$interval = $end->diff($start);

// total days
$days = $interval->days;

// create an iterateable period of date (P1D equates to 1 day)
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

// best stored as array, so you can add more than one
$holidays = array('2012-09-07');

foreach($period as $dt) {
    $curr = $dt->format('D');

    // substract if Saturday or Sunday
    if ($curr == 'Sat' || $curr == 'Sun') {
        $days--;
    }

    // (optional) for the updated question
    elseif (in_array($dt->format('Y-m-d'), $holidays)) {
        $days--;
    }
}


echo $days; // 4

答案 2

在我的情况下,我需要与OP相同的答案,但想要一些更小的东西。@Bojan的答案有效,但我不喜欢它不适用于对象,需要使用时间戳,并且正在与实际对象本身进行比较(这感觉很黑客)...以下是他答案的修订版。DateTimestrings

function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $days = 0;

    while($startDate->diff($endDate)->days > 0) {
        $days += $startDate->format('N') < 6 ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
    }

    return $days;
}

根据@xzdead的评论,如果您希望包含开始结束日期:

function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $isWeekday = function (\DateTime $date) {
        return $date->format('N') < 6;
    };

    $days = $isWeekday($endDate) ? 1 : 0;

    while($startDate->diff($endDate)->days > 0) {
        $days += $isWeekday($startDate) ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
    }

    return $days;
}

推荐