Jump to content

Finding Time range between two given times in Php


mflevie44

Recommended Posts

explode the time on the : (colon) into $hour and $min variables. Compare $hour is between 7 and 20. Example code

$time = '7:45';

list($hour, $min) = explode(':', $time);

if($hour >= 7 && $hour <= 20) {
   // time is ok
} else {
   // time is out of range
}

7:15 would also be a correct entry with that logic :(

$t1 = '7:30';
$t2 = '20:30';
$dt1 = DateTime::createFromFormat('G:i', $t1);
$dt2 = DateTime::createFromFormat('G:i', $t2);

$test = array ('7:15', '7:30', '12:00', '20:00', '20:30', '20:45');

foreach ($test as $t) {
    $dt = DateTime::createFromFormat('G:i', $t);
    $res = $dt1 <= $dt && $dt <= $dt2 ? 'OK' : 'Error';
    echo "$t $res<br>";
}

/* results ****

7:15 Error
7:30 OK
12:00 OK
20:00 OK
20:30 OK
20:45 Error
***************/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.