-1

I have seen this question in many formats, including C/C+ and Javascript. I've also seen this question in it's converse form... How to calculate a span between dates excluding weekends or holidays. But, just suppose you already have a specific date. Let's say, for example, 2014-01-04 and I would like to calculate a date ($diff) three WORKING days before that excluding any weekends or holidays. A direct subtraction of three days would result in 2014-01-01, so we know that won't work. So, I subtract another day and get 2013-12-31 - again, no good. Another attempt gives us 2013-12-30. Finally, we have three ACTUAL WORKING DAYS between the two dates!! But, let's just say that as it will in 2014, 2013-12-30 falls on a Sunday.... man, oh man - shafted again! Well, I think you get my point here. How in the world do I get the results I want?

Community
  • 1
  • 1
DevlshOne
  • 8,357
  • 1
  • 29
  • 37

1 Answers1

-1

Well, I've written a nifty PHP function to work through this dilemma and would like to share it with my fellow coders and accept constructive criticism on it's composition.

function onlyWorkDays( $d ) {
    $holidays = array('2013-12-25','2013-12-31','2014-01-01','2014-01-20','2014-02-17','2014-05-26','2014-07-04','2014-09-01','2014-10-13','2014-11-11','2014-11-27','2014-12-25','2014-12-31');
    while (in_array($d->format("Y-m-d"), $holidays)) { // HOLIDAYS
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 6) { // SATURDAY
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 0) { // SUNDAY
        $d->sub(new DateInterval("P2D"));
    }
    return $d;
}
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
  • The check for weekend must also be in the while loop. Test your function with '2015-12-27' and you will end up on Friday 25. of December. – Paul Spiegel Dec 19 '15 at 09:24