carl carl - 3 months ago 9
PHP Question

Is time within a range? Always returns false

I have written this simple PHP code to tell me whether the current time has passed and whether it is less than 6am.

The current time is 17:56, but this code echos "no".

What is going wrong?

$hourMin = date('H:i');
if ($hourMin >= strtotime('17:00') && $hourMin <= strtotime('06:00')) {
echo "Yes";
} else {
echo "No";
}

Answer

You have a logic problem. How can can something be greater than 17:00 hours and also subsequently less than 06:00 hours? That is why it will always print no.

You have essentially created if (1==0) { echo "Yes" } Surely you see that will never ever happen.

EDIT:

You also need to wrap $hourMin in strtotime

if (strtotime($hourMin) >= strtotime('17:00') || 
    strtotime($hourMin) <= strtotime('06:00')) {