Search code examples
phptimetimestampcompare

How to check if a "start time" is not later than "end time" in PHP


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 !


Solution

  • <?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.