tags:

views:

39

answers:

4

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

+4  A: 

You can use the regex:

(0[0-9]|1[0-2]):[0-5][0-9] [AP]M
codaddict
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.
Tatu Ulmanen
I am not getting this part `(0[0-9]|1[0-2])` what it means, if you can explain. Thanks!
Prashant
@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`.
codaddict
As far as i see, this does not match something like `11:42 AM`, since `1` is not allowed as the first digit.
elusive
But times can also be as 03:35 PM ? then I think second condition of `1[0-2]` will fail?
Prashant
+1  A: 

Check this one http://regexlib.com/REDetails.aspx?regexp_id=1010

Zlatin Zlatev
+1  A: 

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

Phil Brown
+1  A: 

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.

elusive
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?
Prashant
@Prashant: Thats right. This will match 12 hour format only.
elusive
@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
@Prashant: You will get something like this: `11:51 AM` results in `array(0 => '11', 1 => '51', 2 => 'AM')`.
elusive
Thanks @elusive, that's what I needed. :)
Prashant
@Prashant: You're welcome! I just corrected a small error (`10` was missing for the hours part). Be sure to use the latest version!
elusive