Lee Englestone
Lee Englestone

Reputation: 4667

Regular Expression for dd/MM/yyy or dd/MM/yyyy hh:mm:ss

I'll admit I'm rubbish at regular expressions and find some of the tools out there that are supposed to make generating them easier painfully difficult to use. That's my fault granted.. anyway..

Can anyone come up with a single regular expression that will allow both dd/MM/yyyy and/or dd/MM/yyyy hh:mm:ss

Yes, I've Googled for it and searched regexlib.

It would be much appreciated.

Cheers in advance.

UPDATE :

Guys, I obviously considered server side parsing.. I am asking specifically for a regex. I may still fall back on this.

I have also looked at lots of online material including sites that a quick Google brings up, so please don't submit obvious sites as i've tried them and resorted to asking the question here.

UPDATE :

Guys, I'm leaning towards doing it via server side date parsing.. But I would still be curious what the regex would be.

Upvotes: 1

Views: 8199

Answers (6)

Watz
Watz

Reputation: 849

Reg Ex:

^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}( [0-9]{2}:[0-9]{2}:[0-9]{2} (A|P|a|p)(M|m))?$

E.g.

5/31/2016 12:00:00 PM

5/31/2016

5/3/2016

05/3/2016 12:00:00 PM

5/3/2016 12:00:00 PM

5/3/2016 12:00:00 AM

Upvotes: 0

Dhrumil Shah
Dhrumil Shah

Reputation: 2176

This works for me

^(0[1-9]|[12][0-9]|3[01])[-]?(0[1-9]|1[0-2])[-]?(18|19|20|21)\\d{2} ([0-2][0-4]:[0-5][0-9]:[0-5][0-9])$

Valid data format is 25-03-2014 24:10:10 if you need to validate for 25/03/2014 24:10:10 use this

^(0[1-9]|[12][0-9]|3[01])[/]?(0[1-9]|1[0-2])[/]?(18|19|20|21)\\d{2} ([0-2][0-4]:[0-5][0-9]:[0-5][0-9])$

Upvotes: 0

Mike Hanson
Mike Hanson

Reputation: 1089

This should work fine, and does most validation (except for number of days in months):

([0-2][0-9]|3[0-1])/(0[1-9]|1[0-2])/[0-9]{4}( ([0-1][0-9]|2[0-3])(:[0-5][0-9]){2})?

You could add month-wise intelligence to the days, but the RegEx expression for that would look rather hairy.

Upvotes: 0

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

Here is one

[0-9]{2}/[0-9]{2}/[0-9]{4}( [0-9]{2}:[0-9]{2}:[0-9]{2})?

Edit: improved formatting, thanks Nathan Campos.

Or, eliminating many more invalid values:

[0-3][0-9]/[01][0-9]/[0-2][0-9]{3}( [0-2][0-9]:[0-5][0-9]:[0-5][0-9])?

Upvotes: 3

mga
mga

Reputation: 1970

You can try out the different suggestions here: http://www.regexr.com/

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

You're probably better off using DateTime.TryParseExact() for this. It has an overload that allows you to specify multiple possible formats.

Upvotes: 4

Related Questions