Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

datetime

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

like image 990
saurav2109 Avatar asked Jan 13 '11 08:01

saurav2109


1 Answers

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 :)

like image 160
Jon Skeet Avatar answered Oct 03 '22 20:10

Jon Skeet