carl carl - 1 year ago 68
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 Source

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.


You also need to wrap $hourMin in strtotime

if (strtotime($hourMin) >= strtotime('17:00') || 
    strtotime($hourMin) <= strtotime('06:00')) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download