Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for 12hr and 24hr time format

Tags:

c#

regex

asp.net

I am using two regex for validating time in 12hr and 24hr format,but in some cases it is not working.Am i doing something wrong in these regex?It is not working

For validating 12 hr format like 10:00 AM/12:00 PM i have used regex

^(([0]?[0-9]|1[0-2]):[0-5][0-9][ ][aApP][mM])|((1[3-9]|2[0-3]):[0-5][0-9])$

For validating 24 hr format like 23:00/12:00 i have used regex

^(([0]?[0-9]|1[0-2]):[0-5][0-9])|((1[3-9]|2[0-3]):[0-5][0-9])$
like image 527
F11 Avatar asked Sep 30 '13 05:09

F11


People also ask

How does regular expression validate time in 12-hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

How does regular expression validate time in 24-hour format?

On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›. Again, the question mark allows the first 10 hours to be written with a single digit.


1 Answers

I'm not sure why you have some of the 24 hr format in your first regex. The 12 hr format alone could be simplified to this:

new Regex(@"^(?:0?[0-9]|1[0-2]):[0-5][0-9] [ap]m$", RegexOptions.IgnoreCase);

And for the 24 hr format, you can simplify it to:

new Regex(@"^(?:[01][0-9]|2[0-3]):[0-5][0-9]$");

Or to combine both:

new Regex(@"^(?:(?:0?[0-9]|1[0-2]):[0-5][0-9] [ap]m|(?:[01][0-9]|2[0-3]):[0-5][0-9])$", RegexOptions.IgnoreCase);
like image 111
Jerry Avatar answered Oct 17 '22 12:10

Jerry