I decided to write this post because I always encounter some members in the forums.asp.net uses DateTime.Parse method when they try to convert a date string that comes from a TextBox value into a DateTime type (see this forum thread ). Please note that there are certain case why the DateTime.Parse method fails, consider this scenario below:
* If the user enters a non valid date formats in the TextBox then the method DateTime.Parse will throw a FormatException because the method cannot recognize the date format supplied.
We could use the methods Convert.ToDateTime or DateTime.TryParse if the TextBox value will be validated first for a valid format before passing the values to those methods. But just to be always safe then then I would recommend to use DateTime.TryParse method to avoid unexpected exceptions especially when accepting inputs from the users.
Here's an example below:
DateTime datetime;
// in your case set the TextBox value here
string dateStringFormat = "5/26/2009";
//If the string has a valid format then convert it to appropriate format
if (DateTime.TryParse(dateStringFormat, out datetime)) {
Response.Write("String is a valid DateTime format");
//do something
}
else{
Response.Write("String is Not a valid DateTime format");
}
Hope you will find this post useful!
Technorati Tags:
ASP.NET,
C#