0
votes

I have a FromDate and ToDate and days interval between them. 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.

In below example, i have calculated all date between 7/27/2018 and 8/27/2018 with 5 days interval between them,

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.

If any occurence of date after calculating interval in between saturday and sunday then skip this weekend by 1 or 2days.

1
Why tag cakephp ? One solution could be to calcul ALL date between begin and end and then test if the date is sunday or saturday and remove it in this case - Mickaƫl Leger
Bcoz i m using cakephp 3.x...yes u r right bt how to do this..i dont know.. - Rajnikant Bajpai
I updated my code..what i tried - Rajnikant Bajpai

1 Answers

0
votes
$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);