简体   繁体   中英

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.

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.

$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.

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";
}

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