简体   繁体   English

检查 PHP 中的当前日期是否为周末总是失败

[英]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.无论出于何种原因,即使当前日期是星期六,getWeekend() function 也总是返回 false。 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.它肯定会抛出异常,因为date()返回的值是今天的Friday

You can check the function for Saturday by by setting the $today = 'Saturday';您可以通过设置$today = 'Saturday';来检查周六的 function; Or you can try tomorrow it will work perfectly as desired.或者您可以在明天尝试,它会根据需要完美运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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