aussiedan
aussiedan

Reputation: 341

Using PHP how do I include Saturday into my business days?

I've managed to get the following code to work for 'weekdays' and exclude my special days, however:

I'm offering a '7 business days no deposit layby' though my shop is only closed on Sundays. So I need my 'weekday' to include all Saturday's.

$tdate = date("Y-m-d");
$specialdays = ['22-09-2017', '03-10-2017', '14-11-2017', '17-12-2017'];
$i = 7;
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' 
Weekday'));

while (in_array($sevenbusinessdays, $specialdays)) {
   $i++;
   $sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday'));
}

I believe using the above code the answer is something to do with

date('w', strtotime($tdate)) == 6

Though I'm unsure how to incorporate it. I've tried the following but it's not working:

$tdate = date("Y-m-d");
$specialdays = ['22-09-2017', '03-10-2017', '14-11-2017', '17-12-2017'];
$i = 7;
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday' . date('w', strtotime($tdate)) == '6'));

while (in_array($sevenbusinessdays, $specialdays)) {
    $i++;
    $sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday' . date('w', strtotime($tdate)) == '6'));
}

print $sevenbusinessdays;

This completely failed haha, any guidance and help would be greatly appreciated. I think I'm close, just not getting it.

Thanks for any help, it's greatly appreciated it. :-)

Upvotes: 2

Views: 97

Answers (1)

ishegg
ishegg

Reputation: 9937

You need to to a loop, adding days if:

  • it's not a sunday OR
  • it's not in the special days list

until you've added 7 days

<?php
$tdate = date("Y-m-d");
$specialdays = ['15-09-2017', '20-09-2017', '14-11-2017', '17-12-2017'];
$days = 0;
$i = 0;
while ($days < 7) {
    $i++;
    $day = strtotime($tdate . ' +' . $i . ' day');
    if (date("w", $day) === "0" || in_array(date("d-m-Y", $day), $specialdays)) {
        continue;
    }
    $days++;
}
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' day'));
echo $sevenbusinessdays;

Demo

Upvotes: 1

Related Questions