简体   繁体   中英

How can I compare hours:minutes with time variable in PHP?

I wrote the following, however it doesn't seem to work.

What am I missing here?

Thank you

$ora_tora = date('H:i', strtotime('+2 hours')); 
     if (($ora_tora >= '00:00') && ($ora_tora < '02:00')) { echo '1'; }
else if (($ora_tora >= '02:00') && ($ora_tora < '04:00')) { echo '2'; }
else if (($ora_tora >= '04:00') && ($ora_tora < '06:00')) { echo '3'; }
else if (($ora_tora >= '06:00') && ($ora_tora < '08:00')) { echo '4'; }
else if (($ora_tora >= '08:00') && ($ora_tora < '10:00')) { echo '5'; }
else if (($ora_tora >= '10:00') && ($ora_tora < '12:00')) { echo '6'; }
else if (($ora_tora >= '12:00') && ($ora_tora < '14:00')) { echo '7'; }
else if (($ora_tora >= '14:00') && ($ora_tora < '16:00')) { echo '8'; }
else if (($ora_tora >= '16:00') && ($ora_tora < '18:00')) { echo '9'; }
else if (($ora_tora >= '18:00') && ($ora_tora < '20:00')) { echo '10'; }
else if (($ora_tora >= '20:00') && ($ora_tora < '22:00')) { echo '11'; }
else if (($ora_tora >= '22:00') && ($ora_tora < '00:00')) { echo '12'; }

since you actually compare hours you can do:

$ora_tora = (int)date('G', strtotime('+2 hours'));
if ($ora_tora > 2 && $ora_tora < 4) {

}

You could replace all of that with this:

echo intdiv(date('G', strtotime('+2 hours')), 2) + 1;

'G' is the format for 24 hours without leading 0 (so from 0 to 23)

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