I am trying to add 2 weekdays to a date, but I also want to exclude the days in an array.
array of dates to exclude:
$bankHolidays = array(); foreach($obj as $e) { if($e->division == 'england-and-wales') { foreach($e->events as $events) { $bankHolidays[] = $events->date; } } }
Adding 2 working days to date
$ret = date('d-m-Y', strtotime($bill["charge_customer_at"]. ' +2 weekdays'));
How can I include the array of dates to exclude?
As an example, if my date was 2017-07-19
and i want to add 2 week days, that would output 2017-07-21
.
But if 2017-07-21
was in my array, it should skip this date and continue adding 2 weekdays so the output would end up being 2017-07-24
because of the weekend as well.
2 Answers
Answers 1
You could do something as simple as use a while
loop.
$date = '2017-07-25'; $reserved = ['2017-07-27', '2017-07-28']; $days = 2; while ($days > 0) { $date = date('Y-m-d', strtotime($date . ' +1 weekday')); if (! in_array($date, $reserved)) $days--; } var_dump($date);
Answers 2
Find the next business day function with a given offset.
The following basically takes your given date, the number of days you want to skip, in your case 2, and the holidays array that you prepopulate as you show in your question. If the weekday that's so many after your date is a holiday it adds a day and checks again.
function nextBusinessDay($date, $daysToSkip,$holidays){ $day = date('Y-m-d',strtotime($date. ' + '.$daysToSkip.' weekday')); if(!in_array($day,$holidays)){ return $day; } else { return nextBusinessDay(date('Y-m-d',strtotime($date.' +1 day')), $daysToSkip,$holidays); } } $date = '2017-07-19'; $holidays = ['2017-07-21']; echo nextBusinessDay($date,2,$holidays);//returns 2017-07-24 $date = '2017-07-19'; $holidays = ['2017-07-21', '2017-07-24']; echo nextBusinessDay($date,2,$holidays);//returns 2017-07-25 like if it were a 4 day weekend
Sorry it took me a while to get a chance to look it over and post something. This should work for you. My understanding is that you need to return the first business date that is two days from a given date, not keep adding two week days until the date isn't in your holidays array. If you really want to keep adding 2 days, or however many days, then change
return nextBusinessDay(date('Y-m-d',strtotime($date.' +1 day')), $daysToSkip,$holidays);
to
return nextBusinessDay(date('Y-m-d',strtotime($date.' +'.$daysToSkip.' day')), $daysToSkip,$holidays);
0 comments:
Post a Comment