简体   繁体   中英

Find next business date within the 5-7days, skipping weekend or non working days in php?

I'm working with an shopping site which delivers consignments through UK mail with an expected delivery time of 7 days.

So I have set the expected delivery date as:

      // gives me the date 7 days into the future
      $expectedDate=Date('Y:m:d', strtotime("+7 days")); 

Everything was working fine until the UK mail API to which I passed the date returned the following error:

[Errors] => stdClass Object
  (
      [UKMWebError] => stdClass Object
          (
              [Code] => 8200
              [Description] => Validation failed. 05/06/2012 is not a working day.
          )
   )

For example, 05/06/2012 was a Tuesday, but I didn't know it was a holiday. Because it was a holiday, it was rejected.

What I would like to do:

  1. determine an expected delivery date within a range of 5-7 days

  2. which skips weekends

  3. and if I have list of holidays in an array then to skip those dates or give me date within the range of 5-7 days

  4. one thing more I would like to add for example for now the holidays array that need to be skipped only contains this value can you update your answer "05/06/2012"

Is it possible? Can someone show a working example ??

$holidays = array('05/06/12');

$deliverable_days = 1;
$any_day = 1;

while($deliverable_days<=7)
{

 $ts= strtotime("+{$any_day} days");
 $this_date = date('d/m/Y',$ts);
 $this_day = date('w',$ts);

 if(!in_array($this_date,$holidays) && !in_array($this_day,array(0,6)))
 {
  $deliverable_days++;
 }
 if($deliverable_days==7)
 {
   break;
 }
 $any_day++;
}

This won't solve your problem, but you can use it for checking a future date for weekend, holidays, or working day:

// M/d/Y 
$holidays = array(
    '05/06/2012',
    '10/07/2012',
);

$expectedDate = strtotime("+7 days"); 

if (in_array(date('l', $expectedDate), array('Saturday', 'Sunday'))) {
    echo 'weekend';
} else if (in_array(date('m/d/Y', $expectedDate), $holidays)) {
    echo 'holiday';
} else {
    echo date('Y:m:d', $expectedDate) . ' is working day!';
}

Update:

Pinaldesai's answer is very good. It can be simplified like this:

$offset = date('N') < 5 ? 7 : (5 + (7 - date('N')));
$delivery_date = date('Y/m/d', "+$offset days")); 

Below Code will give you delivery date beetween 5-7 days excluding weekends

$working_day    = date('N');

if($working_day < 5)
{
    $delivery_date = date('Y/m/d', strtotime("+7 days")); 
}
else
{
    if($working_day == 6)
        $delivery_date = date('Y/m/d', strtotime("+6 days")); 
    if($working_day == 7)
        $delivery_date = date('Y/m/d', strtotime("+5 days")); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM