1

I am using following regex to validate date in format dd/mm/yyyy in php:

preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $e_startdate, $matches)

But what will be the regex to validate time in the format 10:20 PM or AM. I want a regex which will validate following format for me.

<number><number><colon><number><number><space><AM or PM>

Thanks

5 Answers 5

5

You can use the regex:

(0[0-9]|1[0-2]):[0-5][0-9] [AP]M
Sign up to request clarification or add additional context in comments.

5 Comments

The preceding 0 should be optional to accept times in format 1:23 AM' and this would accept '00:00 AM' or '00:49 PM' which are illegal. (0[1-9]|[1-9]|1[0-2]):[0-5][0-9] [AP]M` should work for those.
I am not getting this part (0[0-9]|1[0-2]) what it means, if you can explain. Thanks!
@Prashant: It means 0[0-9] or 1[0-2]. 0[0-9] means 0 followed by any digit. and 1[0-2] means 1 followed by 0 or 1 or 2.
As far as i see, this does not match something like 11:42 AM, since 1 is not allowed as the first digit.
But times can also be as 03:35 PM ? then I think second condition of 1[0-2] will fail?
3

The following should validate the format you requested:

preg_match("/(\d{2}):(\d{2}) (AM|PM)/", $e_startdate, $matches);

Note that this is not necessarily a valid time. You could enter stuff like 32:62 AM. You need something like this for time validation:

preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", $e_startdate, $matches);

Mind to match the whole thing case-insensitive (like i did in the second example). Otherwise lowercase am, pm, etc. are not going to work.

4 Comments

I want to accept time in 12 hours format only, so your regex /(0?\d|11|12):(0\d|[0-5]\d) (AM|PM)/i this will only accept 12 hours format right?
@elusive: after matching it with preg_match what I'll get in $matches variable? I need HH MM and AM|PM as separate array element in $matches variable?
@Prashant: You will get something like this: 11:51 AM results in array(0 => '11', 1 => '51', 2 => 'AM').
@Prashant: You're welcome! I just corrected a small error (10 was missing for the hours part). Be sure to use the latest version!
3

Regular Expression:

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

Validates time in MySQL time format. 24 hour time colon separated hours:minutes:seconds hh:mm:ss

Matches: 09:30:00 | 17:45:20 | 23:59:59

Non-Matches: 24:00:00

1 Comment

/([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/ slight simplification
1

/\d{2}:\d{2} (AM|PM)/

Comments

0

I started with elusive's answer, but needed a bit more flexibility. This one makes the minutes optional, as well as the space before AM/PM

/(0?\d|1[0-2])(:(0\d|[0-5]\d))?[ ]?(A|P)M/i

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.