saurav2109
saurav2109

Reputation: 61

How to check whether date is in mm/DD/yyyy format or not in C#

How do I check whether a date is in mm/DD/yyyy format or not in C#?

Upvotes: 6

Views: 22763

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500275

Note: I'm assuming that you were asking whether a string is a valid date in "MM/dd/yyyy" format. A DateTime itself doesn't have a format, so you can't check that.

Use DateTime.TryParseExact to try to parse it:

string text = "02/25/2008";
DateTime parsed;

bool valid = DateTime.TryParseExact(text, "MM/dd/yyyy",
                                    CultureInfo.InvariantCulture,
                                    DateTimeStyles.None,
                                    out parsed);

Note that I've changed your format string to what I think you mean - I doubt that you really meant the first bit to be minutes, for example.

If you don't want the invariant culture, specify a different one :)

Upvotes: 19

Related Questions