简体   繁体   中英

Check if the current date is weekend in PHP always fails

Hello all I have two functions. One to check if current day is weekday and if so return a string of the current day. The other to check if current day is weekend and if so return a string of the current day.

For whatever reason the getWeekend() function always return false even if current date is saturday. Please see code below. Maybe I am doing something wrong....

public function getWeekday()
{
    date_default_timezone_set('America/New_York');

    $today = \date("l");
    if ($today == "Monday") {
        return "Monday";
    } elseif ($today == "Tuesday") {
        return 'Tuesday';
    } elseif ($today == "Wednesday") {
        return 'Wednesday';
    } elseif ($today == "Thursday") {
        return "Thursday";
    } elseif ($today == "Friday") {
        return 'Friday';
    } else {
        throw new \Exception('Not a valid date.');
    }
}

public function getWeekend()
{
    date_default_timezone_set('America/New_York');

    $today = \date("l");

    if ($today == "Saturday") {
        return "Saturday";
    } elseif ($today == 'Sunday') {
        return 'Sunday';
    } else {
        throw new \Exception('Not a valid date.');
    }
}

It will surely throw an exception because the date() is returning the value as Friday for today.

You can check the function for Saturday by by setting the $today = 'Saturday'; Or you can try tomorrow it will work perfectly as desired.

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