Skip to content

Instantly share code, notes, and snippets.

@dhaupin
Last active June 7, 2017 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhaupin/f2da4bbdc579dad825901d4e3f82b8ff to your computer and use it in GitHub Desktop.
Save dhaupin/f2da4bbdc579dad825901d4e3f82b8ff to your computer and use it in GitHub Desktop.
Function: Get date offset accounting for weekends and holidays
<?php
// Requires PHP 5.4+
function getWorkingDaysFrom($start, $amtOfDays) {
$globalDays = 0; // a global addition to $amtOfDays (such as a minimum shipping time of 3 days across all objects)
$amtOfDays = $amtOfDays + $globalDays; // set base amount of days for initial range before calculations applied
$ignore = array('6', '7'); // days of the week to ignore (weekends are 6 & 7) in ISO-8061
$holidays = array(
(new DateTime('first monday of january +1 year'))->format('*-m-d'), // new years day (celebrated)
'*-02-29',
(new DateTime('last monday of may'))->format('*-m-d'), // memorial day
'*-07-04',
(new DateTime('first monday of september'))->format('*-m-d'), // labor day
(new DateTime('fourth thursday of november'))->format('*-m-d'), // thanksgiving
'*-12-25'
); // holiday dates (holidays are ignored if they fall into ignore list)
$oneDay = new DateInterval('P1D');
$from = new DateTime($start);
$to = new DateTime($start);
$to->add(new DateInterval('P' . $amtOfDays . 'D'));
foreach(new DatePeriod($from, $oneDay, $to) as $day) {
if (in_array($day->format('N'), $ignore)) {
$to->add($oneDay);
} elseif (in_array($day->format('*-m-d'), $holidays)) {
$to->add($oneDay);
}
while (in_array($to->format('N'), $ignore) || (!in_array($to->format('N'), $ignore) && in_array($to->format('*-m-d'), $holidays))) {
$to->add($oneDay);
}
}
return $to->format('Y-m-d'); // returns a date (or you can format as $to if you need an object)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment