If statement returning false result using date and strtotime

Tags: , ,



I’m trying to use an if statement to say “If today is between two dates, do this…” etc.

It’s not working, and I’m at a total loss because as far as I can see – it SHOULD work!

if (date('d/m/y', strtotime('now')) >= date('d/m/y', strtotime('1 January 2021')) && date('d/m/y', strtotime('now')) <= date('d/m/y', strtotime('31 January 2021'))):
    echo 'true';
else:
    echo 'false';
endif;

Today is 3rd of December 2020 – so why is it telling me this statement is true?

PS. It does work if I change it to either, or both > 30th December 2020 and < 1st February 2021 – but I’m wary to do this in case it’s just a glitch and I’ve made an obvious coding mistake.

Answer

date('d/m/y') gives you a string like 30/11/20. Comparing dates in this format really means you’re comparing strings, which only works if the dates are in YYYYMMDD (or YYYY-MM-DD) format.

It’s much easier to just use strtotime() to turn the English-like date into a Unix timestamp (just a big integer) and compare them directly:

if ( 
    strtotime('now') >= strtotime('1 January 2021')
        &&
    strtotime('now') <= strtotime('31 January 2021')
) {
    echo 'true';
} else {
    echo 'false';
}


Source: stackoverflow