Skip to content
Advertisement

PHP check if time falls within range, questioning common solution

I have to check if the current daytime falls in a specific range. I looked up the internet and found several similar solutions like this one:

$now = date("His");//or date("H:i:s")

$start = '130000';//or '13:00:00'
$end = '170000';//or '17:00:00'

if($now >= $start && $now <= $end){
echo "Time in between";
}
else{
echo "Time outside constraints";
}

If both conditions have to be true, how can this bis achieved when we assume that $start is 06:00:00 and $end is 02:00:00.

If we make the assumption that it is 01:00:00, in this case the first condition can’t be true.

Has anybody an idea to handle this problem differently?

Thanks!

Advertisement

Answer

Naturally, you’d have to account for date in your comparisons.

<?php

$start = strtotime('2014-11-17 06:00:00');
$end = strtotime('2014-11-18 02:00:00');

if(time() >= $start && time() <= $end) {
  // ok
} else {
  // not ok
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement