Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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.Parse 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: ,
Posted on Wednesday, May 27, 2009 11:28 PM ASP.NET , C# | Back to top


Comments on this post: Why Use DateTime.TryParse?

# re: Why Use DateTime.TryParse?
Requesting Gravatar...
Yes, I think it's very useful :) It's just what I searched !
Left by Forex on May 17, 2011 3:11 PM

# re: Why Use DateTime.TryParse?
Requesting Gravatar...
I certainly found it helpful.

Thank you!
Left by Steve on Sep 17, 2011 1:18 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net