11

I'm allowing users to pick an hour from 00:00:00 to 23:00:00 and need to check if they submit the right format. Is there a regular expression or php function that validates a 24 hour format e.g. HH:MM:SS?

I found some regex examples but the 24 hour time I'm validating is always set to 00 for minutes and seconds. Only the hour varies.

For example

18:00:00, 23:00:00, 01:00:00
6
  • Users can alter the selection they made? e.g., imputing "25:00:00" or "banana" ?
    – Zuul
    Jun 12, 2012 at 22:26
  • sachleen's answer is what you've asked for, but if your real problem is providing a user a way to enter a number between 00 and 23, consider using a drop down menu. Jun 12, 2012 at 22:29
  • @Zuul sure they can, they're selecting the time from a dropdown list Jun 12, 2012 at 22:29
  • Data validation is always a real problem, regardless of the UI.
    – Matthew
    Jun 12, 2012 at 22:29
  • @Matthew, agreed, just trying to find out the users "pick" method! To see if the problem was stating at the validation process!
    – Zuul
    Jun 12, 2012 at 22:33

7 Answers 7

22

This matches 24 hour time including seconds

([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

If you only want 00 for minutes and seconds, then

([01]?[0-9]|2[0-3]):00:00
3
  • I forgot to ask..would the following delimiters be correct for regex 2? /^([01]?[0-9]|2[0-3]):00:00$/ Jun 17, 2012 at 21:29
  • 2
    The ^ means start of string and $ end of string. So with those in it, there can be nothing surrounding the time. So yes, that will not only work, it's the right thing to do.
    – sachleen
    Jun 17, 2012 at 22:09
  • awesome! Thank you for your kind confirmation :) Jun 17, 2012 at 23:12
5

Try This

$time="23:00:00";

preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $time);
1
5

Here its a final sample there are ready to be used.

$myTime = '23:00:00';

$time = preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $myTime);

if ( $time == 1 )
{
  // make a error!
}
else
{
  // make a error!
}
2

Check it by this function and you can add this function in CodeIgniter helper file of Laravel global helper functions file and call it more times

<?php
if(!function_exists("check_24_timeFormat")) {
    /**
     *
     * This for check time is in  24 time format  
     * 
     * @param string $time  [ $time => time in 24 hours format like 23:00:00 ]
     * @author Arafat Thabet <[email protected]> 
     * @return bool
     */
    function check_24_timeFormat($time){
        if (preg_match("#((0([0-9])|(1[0-9]{1})|(2[0-4])):([0-5])([0-9]):([0-5])([0-9]))#", $time)) {
            return true;
        }
        else
        {
            return false;
        }
    }
}
1

Has it to be a RegEx? You can easily use PHPs strtotime-function to validate dates and times (does also work without a date). strtotime returns false (-1 prior to PHP 5.1) if the given time isn't valid. Don't forget to use the === operand therefore!

if (strtotime("12:13") === false) { echo("Wrong Time!"); } // Echos nothing
if (strtotime("19:45") === false) { echo("Wrong Time!"); } // Echos nothing
if (strtotime("17:62") === false) { echo("Wrong Time!"); } // Echos 'Wrong Time!'
1
  • This is a really bad answer. As handy as strtotime() is it doesnt do what the question asks. It allows dates and all sorts of expressions. The user really needs a RegExp.
    – omarjebari
    Sep 1, 2021 at 17:46
0

This worked like a charm for me.

$time = "23:59:60";    
preg_match("/^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $time)
0

Although the selected answer is absolutely fine, I'm not a stickler for imposing formats. I'm of the frame of mind that if you can interpret the data, then the format doesn't really matter. Of course the loser you are with formats, the more assumptions you make, and the more risk you take. But providing a confirmation screen usually fixes assumptions. So, I wrote:

/* Sample usage:
 *  echo '<ol>',
 *       '<li>validateTime ("13:23") = ',       (validateTime ('13:23')     ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 ") = ',      (validateTime ('03:23 ')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 Am") = ',    (validateTime ('03:23 aM')  ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23Am") = ',     (validateTime ('03:23aM')   ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 pM") = ',    (validateTime ('03:23 pM')  ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("323") = ',         (validateTime ('323')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("058") = ',         (validateTime ('058')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("1323pm") = ',      (validateTime ('1323pm')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("1323am") = ',      (validateTime ('1323am')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE - I think this one makes sense, but I'm not sure. 13th hour of the day, starting in the AM?
 *       '<li>validateTime ("323pm") = ',       (validateTime ('323pm')     ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("3") = ',           (validateTime ('3')         ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("3PM") = ',         (validateTime ('3PM')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("13:73") = ',       (validateTime ('13:73')     ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '<li>validateTime ("25:23") = ',       (validateTime ('25:23')     ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '<li>validateTime ("Any crap") = ',    (validateTime ('Any crap')  ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '</ol>';
 */
function validateTime ($testTime)
{
    define ('regExpPattern', '/^([01]?[0-9]|2[0-3])([:]?[0-5][0-9])?[ ]?([apAP][mM])?$/');

/*      regExpPattern explanation
            /^          # String must begin with.
            (           # Start group.
            [01]        # A 0 or 1.
            ?           # Optionally.
            [0-9]       # 0 through 9.
            |           # Or.
            2           # 2.
            [0-3]       # 0 through 3.
            )           # End of group. This group will match hour in a 24 hour clock.
            (           # New group.
            [:]?        # Optional colon.
            [0-5][0-9]  # Minutes, 00 through 59.
            )           # End of group.
            ?           # Make previous group optional.
            [ ]?        # Optional space.
            (           # New group.
            [apAP]      # One of the following 'apAP'.
            [mM]        # One of the following 'mM'.
            )           # End of group.
            ?           # Make previous group optional. This allows for things like 3 o'clock.
            $/          # Must end with. */

    return preg_match (regExpPattern, trim ($testTime));
}   // function validateTime ($testDate)

Please let me know if you see improvements or bugs.

Should I accept other separators. What if someone chooses to enter 13.45? Should that be a valid time? After all, I do know what the user means.

Now the next step would be to take the user's input for all possible formats and make it SQL friendly.

Enjoy,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.