Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

Why Use DateTime.TryParse?

I decided to write this post because I always encounter some members in the forums.asp.net uses DateTime.TryParse 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 TryParse 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;

        string dateStringFormat = "5/26/2009"; // in your case set the TextBox value here

        if (DateTime.TryParse(dateStringFormat, out datetime)) //If the string has a valid format then convert it to appropriate format

        {

            Response.Write("String is a valid DateTime format");

            //do something

        }

        else

        {

            Response.Write("String is Not a valid DateTime format");

        }


Hope you fill find this example post useful!

Print | posted on Wednesday, May 27, 2009 11:28 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: