How to exclude weekends between two date ranges

Multi tool use


How to exclude weekends between two date ranges
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.
cakephp
Bcoz i m using cakephp 3.x...yes u r right bt how to do this..i dont know..
– Rajnikant Bajpai
4 hours ago
I updated my code..what i tried
– Rajnikant Bajpai
4 hours ago
1 Answer
1
$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);
your output are Array ( [2018] => Array ( [7] => ) ) ..i need to get all days as per my expected outout
– Rajnikant Bajpai
4 hours ago
I updated my code..what i tried
– Rajnikant Bajpai
4 hours ago
foreach(new DatePeriod($date_from, $interval, $date_to->add($oneday)) as $day) { $day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) / if($day_num < 6) { / weekday */ $days[$day->format("Y-m-d")] = $data; } }
– Sandeep Bangarh
4 hours ago
No its not working as my expected output..plz try to make a complete answer..else plz see my code for refrence
– Rajnikant Bajpai
4 hours ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
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– Mickael Leger
4 hours ago