Skip to content

Instantly share code, notes, and snippets.

@cesurapp
Last active July 22, 2020 20:26
Show Gist options
  • Save cesurapp/84e7d5d3392b2b6dcd3ae101f89b3f00 to your computer and use it in GitHub Desktop.
Save cesurapp/84e7d5d3392b2b6dcd3ae101f89b3f00 to your computer and use it in GitHub Desktop.
Add Working Day with Holidays
<?php
/**
* Add Working Day with Holidays
*
* @param \DateTimeInterface $first
* @param int|null $weekDay
* @param \DateTimeInterface[]|null $holidays
*
* @return \DateTimeInterface
*/
public function addWorkingDay(\DateTimeInterface $first, ?int $weekDay, ?array $holidays): \DateTimeInterface
{
// Add Week Day
$last = $weekDay ? (clone $first)->modify("+{$weekDay} weekday") : $first;
// Append Holiday
$append = 0;
foreach ($holidays as $index => $holiday) {
// Disable Week Day
$w = (int)$holiday->format('w');
if ($w === 0 || $w === 6) {
continue;
}
if (($holiday >= $first) && ($holiday <= $last)) {
unset($holidays[$index]);
$append++;
}
}
if ($append) {
return addWeekDay($last, $append, $holidays);
}
return $last;
}
@cesurapp
Copy link
Author

Example

$current = new DateTime();
$holidays = [
    new DateTime('2020-07-29'),
    new DateTime('2020-07-30'),
    new DateTime('2020-07-31'),
    new DateTime('2020-08-01'),
    new DateTime('2020-08-02'),
    new DateTime('2020-08-03'),
];

addWeekDay($current, 5, $holidays)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment