tags:

views:

593

answers:

6

Hi,

Can I please have a regular expression in .NET, which will allow only 24 hr time format in the textbox.

Thanks.

Best Regards, MS

+3  A: 

Try this

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

It's 24 hour time with optional seconds. (Source)

JaredPar
+5  A: 

Regular Expressions: Time hh:mm validation 24 hours format:

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

If you need seconds too:

([0-1]\d|2[0-3]):([0-5]\d)(:([0-5]\d))?

Edit: To prevent trailing AM/PM, partial match can't be allowed or you have to put the expression between ^ and $.

^([0-1]\d|2[0-3]):([0-5]\d)(:([0-5]\d))?$
eed3si9n
What about the AM and PM?
MKS
@Manoj: isn't the point with 24 hour clock that you omit AM/PM?
Fredrik Mörk
@Fredrik @eed3si9n, I think Manoj may be saying that this allows AM/PM and shouldn't. It needs anchors to avoid this. ie At the moment it would match 23:15 AM
Ash
@Ash I see. If that's the case, I'll put the expression between ^ and $ like others are suggesting.
eed3si9n
+3  A: 

What about using DatePicker or DateTimePicker depending upon if you're using WPF or Winforms? This might be a better UE anyways.

Taylor Leese
I read your links, but was not able to understand completely. can I have code example using vb.net. How can I use it in my vb.net code. Thanks!
MKS
Just google around. I'm sure you can find some examples. Basically, the point I was trying to make is that you should probably use one of the pre-built date controls if you really want the user to input date/time info.
Taylor Leese
+1  A: 

Try

^([0-1]?\d|2[0-3])(:[0-5]\d){1,2}$
Vanilj
A: 

I would suggest you take a look at The Regulator for next time when you need a regular expression, its a great tool for designing your expressions.

Anders K.
+1  A: 

Personally, rather than go the validation route I would use a control like a datetime picker for the following reasons:

  • Zero validation is required. In fact the only validation you'd do would be business rules validation e.g. Order date cannot be later than today, etc
  • Easier on the user -- you don't have to tell the user to key in the time in 24 hour format
Conrad
http://stackoverflow.com/questions/1360801/net-regular-expression-for-time-24-hr-format/1360842#1360842
Taylor Leese