I'm trying to check if a specific "start time" is not later than another "end time"
For exemple :
Start : 09:00 and End : 11:00 is OK
Start : 10:00 and End : 08:00 is NOT OK
If the "end time" is midnight (00:00), so it's ok because :
Start : 08:00 and End : 00:00 is OK
I managed to do this little function, and it works as I want :
<?php
function isTimeOk($start, $end) {
if (($start < $end) or $end == '00:00') {
return 'Ok';
}
return 'Not ok';
}
echo isTimeOk('09:00', '12:00');
?>
But, I've two questions :
Is there a way to make this code more elegant?
How to make this compatible with the 12 and 24 hour format?
Thanks for your help !
CodePudding user response:
You can use timestamps or convert the time to DateTime:
function isTimeOk(string $start, string $end): bool {
if ($end == '00:00') {
return true;
}
$start_date = DateTime::createFromFormat('H:i', $start);
$end_date = DateTime::createFromFormat('H:i', $end);
return $start_date < $end_date;
}
For more information on time format (including 12/24 clock), visit https://www.php.net/manual/en/datetime.createfromformat.php
CodePudding user response:
<?php
function isTimeOk($start, $end) {
$start = strtotime($start);
$end = strtotime($end);
if (($start < $end) or $end == strtotime('00:00')) {
return 'Ok';
}
return 'Not ok';
}
echo isTimeOk('09:00', '12:00');
?>
strtotime should work.