简体   繁体   English

如何排除两个日期范围之间的周末

[英]How to exclude weekends between two date ranges

I have a FromDate and ToDate and days interval between them. 我有一个FromDate和ToDate以及它们之间的天数间隔。 Now i want to get all date excluding weekends 现在我想获得除周末以外的所有日期

If there is any weekends between my FromDate and ToDate,then this date will be increment by 2 days saturday and sunday. 如果我的FromDate和ToDate之间有任何周末,那么该日期将在周六和周日增加2天。

In below example, i have calculated all date between 7/27/2018 and 8/27/2018 with 5 days interval between them, 在下面的示例中,我计算了7/27/2018至8/27/2018之间的所有日期,它们之间有5天的间隔,

public function testdate(){
            $date_from = new \DateTime("7/27/2018");
            $date_to = new \DateTime("8/27/2018");
            $interval = new \DateInterval("P5D");
            $dates = new \DatePeriod($date_from, $interval, $date_to);
            $out = array();
            if (!empty($dates)) {
                foreach($dates as $dt) {
                    $out[] = array(
                        'month_year' => $dt->format('d/m/Y')
                    );
                }
            }  
            '<pre>';
            //$out = array_reverse($out);
            echo print_r($out); 
            '</pre>'; 
            exit;           
        }

Expected output 预期产量

Array
(
    [0] => Array
        (
            [month_year] => 27/07/2018
        )

    [1] => Array
        (
            [month_year] => 02/08/2018
        )

    [2] => Array
        (
            [month_year] => 08/08/2018
        )

    [3] => Array
        (
            [month_year] => 14/08/2018
        )

    [4] => Array
        (
            [month_year] => 20/08/2018
        )

    [5] => Array
        (
            [month_year] => 27/08/2018
        )

)

In above example, after 20/08/2018, next date will be 26/08/2018 but 26/08/2018 is sunday, so we exclude this sunday by 1 day and next date is now 27/08/2018. 在上面的示例中,在20/08/2018之后,下一个日期将是26/08/2018,但是26/08/2018是星期日,因此我们将该星期天排除在1天之前,下一个日期现在是27/08/2018。

If any occurence of date after calculating interval in between saturday and sunday then skip this weekend by 1 or 2days. 如果在计算周六至周日之间的间隔后发生日期,则将本周末跳过1或2天。

$year = date('Y');
$month = date('n');

$weekend_days = array_filter($allDays[$year][$month], function($d) {
    return (date('N', strtotime(date("Y-m-$d"))) >= 6);
});

$allDays[$year][$month] = array_diff($allDays[$year][$month], $weekend_days);

print_r($allDays);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM