Jump to content

regular expression that matches the time without the am/pm


kee2ka4

Recommended Posts

Hey Guys,

 

I am a php newbie and need some help to define a regular express rule that would match the time without the am/pm, so the following formates are all true:

 

9:00

09:00

22:30

23:59

00:00 etc

 

Any directions here...

 

Thanks,

Ket

Link to comment
Share on other sites

When needing a validation such as this, it is very important to have explicit, definitive rules. You gave a few examples of what should pass, but it is not enough. The easy approach would be to validate that the string starts with one or two numbers, has a colon, and then has two more numbers. But, that means 25:01 or 10:99 would pass. Is that acceptable? I don't know your situation. Also, if 00:00 is valid is 24:00 valid as well?

 

Here is one possible solution:

function validTimeStr($timeStr)
{
    return (preg_match("/^((\d|[0-1]\d|2[1-3]):[0-5]\d)|24:00$/", $timeStr)>0);
}

 

Output of tests:

00:00: true
1:25: true
01:25: true
001:25: false
11:59: true
2:64: false
23:23: true
24:00: true
24:01: false

 

You should test against anything else you think might be problematic.

Link to comment
Share on other sites

The regex rule you defined its fine but without the ":" right at the end.

 

The ":" at the end was just part of my unit test code couput. It has nothing to do with the function. The function will simply return true/false based upon whether the passed value matches the pattern.

Link to comment
Share on other sites

I'd try a pattern like this:

'/^(0{0,1}[1-9]|1\d|2[0-3])[0-5]\d)$/'

 

That won't work for 24:00 as requirested by the OP. Although, I do see I had an error in my original code for the hour "20". And, that does give me an idea on shortening the original pattern to:

return (preg_match("/^(([0-1]?\d|2[0-3]):[0-5]\d)|24:00$/", $timeStr)>0);

 

- not tested

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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