How to Validate a DateTime in C#?

Matt picture Matt · Dec 16, 2008 · Viewed 338.2k times · Source

I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.

I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box.

try
{
    DateTime.Parse(startDateTextBox.Text);
}
catch
{
    startDateTextBox.Text = DateTime.Today.ToShortDateString();
}

Answer

qui picture qui · Dec 16, 2008
DateTime.TryParse

This I believe is faster and it means you dont have to use ugly try/catches :)

e.g

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
  // Yay :)
}
else
{
  // Aww.. :(
}