Function recursive to get a day that don't be sunday or saturday

142 Views Asked by At

I have a problem with my function, what it does is, see if a date fell on Saturday or Sunday if so, add a day until the day is not Saturday not Sunday, it is supposed that it should return the correct date. For example, I am entering the date 2021-03-20 and it returns the date of 2021-03-21, when 2021-03-22 should return. I do not know what is happening here I leave my function:

enter code here

private function isWeekend($date) {
    // Convert string to time
    // Get day name from the date
    $dt2 = date("l", strtotime($date));
    // Convert day name to lower case
    $dt3 = strtolower($dt2);
    $date_ = $date;
    // Check if day name is "saturday" or "sunday"
        if(($dt3 == "saturday" ) || ($dt3 == "sunday")) {
            // If the date is weekend then
            $date_ = date('Y-m-d', strtotime($date."+ 1 days"));
            $this->isWeekend($date_);
        }
    return $date_;
}
2

There are 2 best solutions below

0
Don R On BEST ANSWER

You aren't capturing the value of the recursive call. Try this:

return $this->isWeekend($date_);

or

$date_ = $this->isWeekend($date_);
0
jspit On

No loop or recursion is required to determine the a day that is not a Saturday or Sunday. We use the relative expression 'next weekday' for this.

Old school solution with strtotime:

$date = '2021-03-20';
$dateIsWeekday = date('Y-m-d',strtotime('next weekday',strtotime('-1 day',strtotime($date))));
// "2021-03-22"

The solution with strtotime is tricky and confusing. To use the DateTime class is better.

$date = '2021-03-20';

$dateTime = date_create($date)
  ->modify('-1 Day')
  ->modify('next weekday')
;
$dateIsWeekday = $dateTime->format('Y-m-d');
// "2021-03-22"