How to Validate a DateTime in C#?


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.

    startDateTextBox.Text = DateTime.Today.ToShortDateString();
12/19/2018 12:38:22 PM

Accepted Answer


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


DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
  // Yay :)
  // Aww.. :(
9/24/2018 8:15:33 PM

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
    startDateTextox.Text = DateTime.Today.ToShortDateString();

Reasons for preferring this approach:

  • Clearer code (it says what it wants to do)
  • Better performance than catching and swallowing exceptions
  • This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow