【问题标题】:Remove weekends from date range从日期范围中删除周末
【发布时间】:2017-10-25 15:31:37
【问题描述】:

我正在使用 this answer 来帮助我,但需要将其解决到我的问题中。

我想计算两个日期之间的天数,然后删除周末。如何结合以下两个答案?

日期 1 是 06.10.2017,日期 2 是 09.10.2017。

$date1 = new DateTime(get_sub_field('start_date'));
$date2 = new DateTime(get_sub_field('end_date'));

$diff = $date2->diff($date1)->format("%a");
echo $diff;

这给了 3 天。我希望它显示 1,因为那里有一个周末。所以我需要将它与以下内容结合起来:

下一个答案将删除所有周末:

function countDays($year, $month, $ignore) {
    $count = 0;
    $counter = mktime(0, 0, 0, $month, 1, $year);
    while (date("n", $counter) == $month) {
        if (in_array(date("w", $counter), $ignore) == false) {
            $count++;
        }
        $counter = strtotime("+1 day", $counter);
    }
    return $count;
}
echo countDays(2017, 10, array(0, 6)); // 22

在 10 月给予 22 个工作日。

如何结合这两个答案来显示两个日期之间的天数,但不包括周末?

【问题讨论】:

标签: php


【解决方案1】:

PHP 日期和时间类非常强大。

我会使用DateIntervalDatePeriod

$start = new DateTime('2017-10-06');
$end   = new DateTime('2017-10-09');
$interval = DateInterval::createFromDateString('1 day');
$period   = new DatePeriod($start, $interval, $end);

$businessDays = 0;
foreach ($period as $day) {
    // $day is not saturday nor sunday
    if (! in_array($day->format('w'), [0, 6])) {
        $businessDays++;
    }
}

echo $businessDays; // prints 1

【讨论】:

  • 该死 - 忍者;)
  • @DanFromGermany 这是一个非常简洁的答案,谢谢。比我在外面看到的任何东西都要好。
  • 删除了我的答案,因为它基本上是相同的(几乎在变量名的后面),因此是多余的;)
  • @CD001 你的有一点改进,它没有在每次迭代时创建一个数组,只是一次。
猜你喜欢
  • 2013-03-01
  • 2023-02-08
  • 1970-01-01
  • 2016-03-20
  • 2018-06-01
  • 2016-02-24
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多