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])$
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] ›.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With