148

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(); } 
5
  • 1
    <sarcasm>judging by the answers, I think I should use TryParse</sarcasm> Thanks for the great answers guys. I had not even thought about TryParse Commented Dec 16, 2008 at 18:17
  • 2
    An example of an easy to google question that if someone asked today would be unfairly closed for having "not enough research". Commented Jun 27, 2013 at 20:39
  • 1
    here is an easy way to do this without using any special functions :<stackoverflow.com/questions/14917203/…> Commented Sep 11, 2013 at 16:20
  • even Parse uses TryParse referencesource.microsoft.com/#mscorlib/system/globalization/… Commented Feb 1, 2017 at 20:40
  • 2
    Working with DateTimes is always a pain in the bass. Thanks Commented Apr 11, 2017 at 6:11

14 Answers 14

314
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.. :( } 
Sign up to request clarification or add additional context in comments.

6 Comments

Correct me if I'm wrong, but in C# (as opposed to, say, JavaScript) doesn't an if/else branch require curly braces? Don't getting me wrong, I'm not trying to scrutinize, it's a fantastic answer and I'm +1ing it because it helped me, but just thought since you never know how new future users are when viewing already posted answers, this could confuse them. Of course, if you're having trouble with curly braces in C#, this question would be the least of your worries...
@VoidKing You are correct about the curly braces but if you only have 1 statement in that block you don't have to use them. This applies in some other languages as well but I can see how this can be misleading to newer coders.
@D.Galvez Excuse my late coming to the party, but is it a best practice to include the brackets even if there is only 1 statement? This might just be a situation where personal preference is most important -- and in that case I find including them to be quite nice simply for readability and consistency.
Little did I know 6 years ago that such a debate about brackets would occur.
It is possible to shorten the variable initialization with if(DateTime.TryParse(startDateTextBox.Text, out var temp)) :)
|
68

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

Comments

28

Here's another variation of the solution that returns true if the string can be converted to a DateTime type, and false otherwise.

public static bool IsDateTime(string txtDate) { DateTime tempDate; return DateTime.TryParse(txtDate, out tempDate); } 

1 Comment

Welcome to StackOverflow! Please look at the answers that have already been provided, especially when responding to a question that's over three years old and has been successfully answered. Your answer has already been covered by previous respondents.
6

All the Answers are Quite great but if you want to use a single function ,this may work. It will work with other date format but wont work with this date eg:05/06/202 it will consider it as valid date but it isnt.

private bool validateTime(string dateInString) { DateTime temp; if (DateTime.TryParse(dateInString, out temp)) { return true; } return false; } 

5 Comments

How about returning the result of DateTime.TryParse() instead of "if" block? Also, your IDE would complain on never used temp, which you could declare inside the function call directly as "out DateTime temp".
@SergeiKovalenko This helps the newbies to understand how TryParse works.
I am pretty sure, newbies should learn how something works in the documentation. And here they should see a better example of usage.
@SergeiKovalenko Please don't comment your personal suggestions here.
As you wish, Sayed.
5

I would use the DateTime.TryParse() method: http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

Comments

4

What about using TryParse?

Comments

4

One liner:

if (DateTime.TryParse(value, out _)) {//dostuff} 

Comments

3

A problem with using DateTime.TryParse is that it doesn't support the very common data-entry use case of dates entered without separators, e.g. 011508.

Here's an example of how to support this. (This is from a framework I'm building, so its signature is a little weird, but the core logic should be usable):

 private static readonly Regex ShortDate = new Regex(@"^\d{6}$"); private static readonly Regex LongDate = new Regex(@"^\d{8}$"); public object Parse(object value, out string message) { msg = null; string s = value.ToString().Trim(); if (s.Trim() == "") { return null; } else { if (ShortDate.Match(s).Success) { s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2); } if (LongDate.Match(s).Success) { s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4); } DateTime d = DateTime.MinValue; if (DateTime.TryParse(s, out d)) { return d; } else { message = String.Format("\"{0}\" is not a valid date.", s); return null; } } } 

2 Comments

I am not worried about seporators in my case because I am using a Masked Text Box, but I can see how that would be handy in other situations I may encounter with this app.
What's the reason to use DateTime string without separators?
2

You can also define the DateTime format for a specific CultureInfo

public static bool IsDateTime(string tempDate) { DateTime fromDateValue; var formats = new[] { "MM/dd/yyyy", "dd/MM/yyyy h:mm:ss", "MM/dd/yyyy hh:mm tt", "yyyy'-'MM'-'dd'T'HH':'mm':'ss" }; return DateTime.TryParseExact(tempDate, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateValue); } 

Comments

1
 protected bool ValidateBirthday(String date) { DateTime Temp; if (DateTime.TryParse(date, out Temp) == true && Temp.Hour == 0 && Temp.Minute == 0 && Temp.Second == 0 && Temp.Millisecond == 0 && Temp > DateTime.MinValue) return true; else return false; } 

//suppose that input string is short date format.
e.g. "2013/7/5" returns true or
"2013/2/31" returns false.
http://forums.asp.net/t/1250332.aspx/1
//bool booleanValue = ValidateBirthday("12:55"); returns false

Comments

1
private void btnEnter_Click(object sender, EventArgs e) { maskedTextBox1.Mask = "00/00/0000"; maskedTextBox1.ValidatingType = typeof(System.DateTime); //if (!IsValidDOB(maskedTextBox1.Text)) if (!ValidateBirthday(maskedTextBox1.Text)) MessageBox.Show(" Not Valid"); else MessageBox.Show("Valid"); } // check date format dd/mm/yyyy. but not if year < 1 or > 2013. public static bool IsValidDOB(string dob) { DateTime temp; if (DateTime.TryParse(dob, out temp)) return (true); else return (false); } // checks date format dd/mm/yyyy and year > 1900!. protected bool ValidateBirthday(String date) { DateTime Temp; if (DateTime.TryParse(date, out Temp) == true && Temp.Year > 1900 && // Temp.Hour == 0 && Temp.Minute == 0 && //Temp.Second == 0 && Temp.Millisecond == 0 && Temp > DateTime.MinValue) return (true); else return (false); } 

Comments

-4
DateTime temp; try { temp = Convert.ToDateTime(grd.Rows[e.RowIndex].Cells["dateg"].Value); grd.Rows[e.RowIndex].Cells["dateg"].Value = temp.ToString("yyyy/MM/dd"); } catch { MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign); grd.Rows[e.RowIndex].Cells["dateg"].Value = null; } 

1 Comment

U have to check valid by try catch . So U can using try catch for checking all types variables and make valid Global Functions and controlling all in your project . best regards ..... Ashraf khalifah
-4
DateTime temp; try { temp = Convert.ToDateTime(date); date = temp.ToString("yyyy/MM/dd"); } catch { MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign); date = null; } 

Comments

-4
protected static bool CheckDate(DateTime date) { if(new DateTime() == date) return false; else return true; } 

2 Comments

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
The question is asking how to validate a string that might or might not contain a DateTIme value. You are checking to see whether a given DateTime has default values (corresponding to 0001-01-01T00:00:00.0000000). How does this answer the question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.