Brendan Lane
Brendan Lane

Reputation: 127

How to get DateTime.TryParse to parse dates in the "ddMMyyyy" format?

I need to parse dates that might be in the format "ddMMyyyy" as well as in the standard GB English formats (e.g. "dd/mm/yyyy"), and I'm trying to use the DateTime.TryParse() method to do it but it doesn't recognise the "ddMMyyyy" format.

I know I can use Date.TryParseExact() and specify the custom format each time, but that means doing two checks for each date (one for the custom format and one for the culture's standard formats) and it just seems that there must be a better way.

Is there a way to get the DateTime.TryParse() method to recognise custom date formats as well as the standard formats?

Upvotes: 1

Views: 657

Answers (3)

Anderson Fortaleza
Anderson Fortaleza

Reputation: 2459

I don't think that it's possible to set DateTime.TryParse() to recognize any of two date formats at the same time. Looking at the overrides for DateTime.TryParse() you have .TryParse(String, DateTime) and TryParse(String, IFormatProvider, DateTimeStyles, DateTime), therefore the maximum of flexibility here lets you provide a IFormatProvider that could be a DateTimeFormatInfo class, but DateTimeFormatInfo can only deal with one set of formats at a time.

One shot (I did not try it) would be to create a new DateTimeFormatInfo class with different LongDatePattern and ShortDatePattern patterns (matching the ones you want to use), and pass the instance as a parameter to TryParse, but checking two times with Date.TryParseExact() seems way more reasonable.

Upvotes: 1

JDB
JDB

Reputation: 25820

I'm afraid that date parsers tend not to be too intelligent, mostly by design. While you may want to parse a "ddMMyyyy" date, someone else may want to parse a "yyyyMMdd" date. In some circumstances, these may be identical (what is "20121220"?). The parser is dumb, and you must tell it which format to use. If you specify multiple formats, then it'd need to try them one at a time, which is exactly what you are trying to avoid.

If you really only want to take a single pass, you could use a regex to extract the pertinent parts ("(?<Day>\d{2})/?(?<Month>\d{2})/?(?<Year>\d{4})") then reconstitute it into a format recognized by the parser (string.Format("{0}/{1}/{2}", match.Groups["Day"].Value, match.Groups["Month"].Value, match.Groups["Year"].Value)).

Honestly, though, it'd probably be more efficient to just use String.Contains("/") in an if statement.

Upvotes: 0

Paritosh
Paritosh

Reputation: 4503

Howw about using DateTime.TryParseExact MSDN link

Upvotes: 0

Related Questions