valid date check with DateTime.TryParse method

Sujit picture Sujit · Jul 3, 2012 · Viewed 45.9k times · Source

I am using Datetime.TryParse method to check the valid datetime. the input date string would be any string data. but is returning false as the specify date in invalid.

DateTime fromDateValue;
if (DateTime.TryParse("15/07/2012", out fromDateValue))
{
    //do for valid date
}
else
{
    //do for in-valid date
}

Edit: i missed. i need to check the valid date with time as "15/07/2012 12:00:00".

Any suggestions are welcome....

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 3, 2012

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

So for example:

DateTime fromDateValue;
string s = "15/07/2012";
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
    // do for valid date
}
else
{
    // do for invalid date
}