Reputation: 143
I am having some difficulties display the next x number of days excluding weekends. The basic code is here which displays all days:
<?php
for($i = 0; $i < 8; $i++) {
echo date('D M j', strtotime("$i day"));
}
?>
I cant then get it to do a continue:
<?php
for($i = 0; $i < 8; $i++) {
$day = date('N', strtotime("$i day"));
if($day == '6' || $day == '7') continue;
echo date('D M j', strtotime("$i day"));
}
?>
But this obviously skips the weekends completely and I don't get x returned days. I have tried reducing the number by 1 but just get timeouts so guessing this is not the way to go.
Upvotes: 0
Views: 38
Reputation: 1366
As CBroe already pointed out, use a variable for the number of days you want to iterate. When you get a saturday or sunday then increment that variable by one. E.g.
<?php
$x = 8;
for($i = 0; $i < $x; $i++) {
$day = date('N', strtotime("$i day"));
if($day == '6' || $day == '7') {
$x++;
continue;
}
echo date('D M j', strtotime("$i day"));
}
?>
The output would always be $x
weekdays, for today it would be
Fri Jan 22Mon Jan 25Tue Jan 26Wed Jan 27Thu Jan 28Fri Jan 29Mon Feb 1Tue Feb 2
Upvotes: 1
Reputation: 33813
If you were to adopt the DateTime
class you could do like this:
$start=new DateTime();
$end=new DateTime('now + 7days');
$interval=new DateInterval('P1D');
$start->sub( $interval );
while( $start < $end ){
$start->add( $interval );
$N=intval($start->format('N'));
if( $N > 0 && $N < 6 ){
echo $start->format('l N Y-m-d H:i:s').'<br />';
}
}
Which yields output like:
Friday 5 2021-01-22 13:22:01
Monday 1 2021-01-25 13:22:01
Tuesday 2 2021-01-26 13:22:01
Wednesday 3 2021-01-27 13:22:01
Thursday 4 2021-01-28 13:22:01
Friday 5 2021-01-29 13:22:01
Upvotes: 1