I've written a program for calculating the future date after certain number of business days.
function add_business_days($startdate,$businessdays,$holidays,$dateformat){
$i=1;
$dayx = strtotime($startdate);
while($i < $businessdays){
$day = date('N',$dayx);
$date = date('Y-m-d',$dayx);
if($day < 6 && !in_array($date,$holidays))$i++;
$dayx = strtotime($date.' +1 day');
}
return date($dateformat,$dayx);
}
But the problem with this function is that it doesn't check the last date of business day for Saturday
and Sunday
. Also, the last day could be the holiday
. Can anyone provide me a better solution for this?
I've made a solution to this problem as
function add_business_days($startdate,$businessdays,$holidays,$dateformat){
$i=1;
$dayx = strtotime($startdate);
while($i <= $businessdays){
$day = date('N',$dayx);
$date = date('Y-m-d',$dayx);
if($day < 6 && !in_array($date,$holidays))$i++;
$dayx = strtotime($date.' +1 day');
}
return date($dateformat,strtotime(date('Y-m-d', $dayx) . ' -1 day'));
}
But it doesn't seems good.
Usage Example
I'm using this method for calculating the shipment date on which a product will be delivered to the customer.
$startdate = "2014-05-28"; //Order placing date
$businessdays = 7; //number of days for delivery
$holidays = array('2014-05-30','2014-06-03'); //array of dates having holidays. excluding business days.
$dateformat = 'd-m-Y'; //output date format for displaying.
$delivery = add_business_days($startdate, $businessdays, $holidays, $dateformat);
The $delivery
is supposed to have date 09-06-2014
but the first code returns 07-06-2014
which doesn't check for the last date in loop for weekends (Saturday or Sunday). I've made the solution in the second program by execution the loop one more time and then return the previous date. But this approach doesn't seem good. Any suggestions on not going over and returning the previous date?