2
\$\begingroup\$

The object is to be able to pass some dates (start date, holiday) and the number of days you want to skip. We only want to skip working days, not weekends and holidays.

Just let me know what you'd do different than what I have. The code works, but I was told there are issues with it, but not told what issues they are.

function getWDays($startDate,$holiday,$wDays){

$d = new DateTime( $startDate );
$t = $d->getTimestamp();
$h = strtotime($holiday);

// loop for $wDays days
for($i=0; $i<$wDays; $i++){

    // 1 day = 86400 seconds
    $addDay = 86400;

    $nextDay = date('w', ($t+$addDay));
    if($nextDay == 0 || $nextDay == 6) {
        $i--;
    }
    $t = $t+$addDay;
    if ($t == $h) {
        // lets make sure the holiday isn't one of our weekends
        if(!$nextDay == 0 || !$nextDay == 6) {
            $t = $t+$addDay;    
        }
    }
}

$d->setTimestamp($t);


return $d->format( 'Y-m-d' );

}

echo getWDays("2013-08-29","2013-09-02", 3)
\$\endgroup\$
2
\$\begingroup\$

Here is another way of doing the same thing

<?php

function getWDays($startDate,$holiday,$wDays) {

    // using + weekdays excludes weekends
    $new_date = date('Y-m-d', strtotime("{$startDate} +{$wDays} weekdays"));

    $holiday_ts = strtotime($holiday);

    // if holiday falls between start date and new date, then account for it
    if ($holiday_ts >= strtotime($startDate) && $holiday_ts <= strtotime($new_date)) {

        // check if the holiday falls on a working day
        $h = date('w', $holiday_ts);
            if ($h != 0 && $h != 6 ) {
            // holiday falls on a working day, add an extra working day
            $new_date = date('Y-m-d', strtotime("{$new_date} + 1 weekdays"));
        }
    }

    return $new_date;
}

// here is an example
$start = "2013-08-29";
$holiday = "2013-09-02";
$wDays = 3;

echo "Start: ",date("Y-m-d D", strtotime($start)),"<br />";
echo "Holiday: ",date("Y-m-d D", strtotime($holiday)),"<br />";
echo "WDays: $wDays<br />";

echo getWDays($start, $holiday, $wDays);
\$\endgroup\$
  • \$\begingroup\$ Thanks for the reply. I like your use of Weekdays. I need to use that more often. Much appreciated. \$\endgroup\$ – pjmetzger Sep 5 '13 at 21:59
  • \$\begingroup\$ what about multiple holidays ? \$\endgroup\$ – Shrikant Oct 12 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.