Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading