简体   繁体   English

为什么用此PHP代码检查昨天是否是银行假期,不工作?

[英]Why is this PHP code to check if yesterday was a bank holiday not working?

I am trying to check if yesterday was a UK bank holiday (using an array of known dates) and then use the boolean variable $bankholyesterday later on in the code to control whether or not an item from an RSS feed is displayed. 我正在尝试检查昨天是否是英国的银行假期(使用一系列已知日期),然后在代码中稍后使用布尔变量$bankholyesterday来控制是否显示来自RSS feed的项目。

For some reason, yesterday is always being identified as a bank holiday, so my control structure is not working as intended. 由于某种原因,昨天总是被确定为银行假日,因此我的控制结构无法正常工作。 Can anyone see where I am going wrong? 谁能看到我要去哪里错了?

$bankhols = array ("02/01/2017", "17/04/2017", "01/05/2017", "29/05/2017", "28/08/2017", "01/01/2018", "02/04/2018", "07/05/2018", "28/05/2018", "27/08/2018", "22/04/2019", "06/05/2019", "27/05/2019", "26/08/2019", "13/04/2020", "04/05/2020", "25/05/2020", "31/08/2020");

$yesterday = date('d/m/Y', strtotime("-1 days"));

$bankholyesterday = false;

foreach ($bankhols as $bankhol) {
    if (strtotime($yesterday) === strtotime($bankhol)) {
        $bankholyesterday = true;
        break;
    }
}

...

if ($bankholyesterday == true) {
    ... do the thing ...
}

You could use in_array instead. 您可以改用in_array

$bankhols = array ("02/01/2017", "17/04/2017", "01/05/2017", "29/05/2017", "28/08/2017", "01/01/2018", "02/04/2018", "07/05/2018", "28/05/2018", "27/08/2018", "22/04/2019", "06/05/2019", "27/05/2019", "26/08/2019", "13/04/2020", "04/05/2020", "25/05/2020", "31/08/2020");

$yesterday = date('d/m/Y', strtotime("-1 days"));

if (in_array($yesterday, $bankhols)) {
//yesterday was bank holiday
} else {
//yesterday was not bank holiday
}

I tested the code and it works. 我测试了代码,它可以工作。 I tried adding yesterdays date in the array $bankhols, and it returned true, and while it's not in the array, it returned false. 我尝试在数组$ bankhols中添加昨天的日期,但返回true,而不在数组中时,返回false。

wrote a short script to convert and compare two dates, as I don't know of any alternative: 我写了一个简短的脚本来转换和比较两个日期,因为我没有其他选择:

function compareDates($date1, $date2) {
    // date1 format = d/m/Y
    // date2 format = m/d/Y

    $d3 = explode("/", $date1);
    $date1 = $d3[1] . "/" . $d3[0] . "/" . $d3[2];

    return $date1 == $date2;
}

if (compareDates("27/11/2016", "11/27/2016")) {
    echo "dates match";
} else {
    echo "dates don't match";
}

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

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