Parsing Dates in C#

In this example: How to parse a string date into a DateTime object. If the parse doesn’t work, we want to just use todays date.

The verbose way

                DateTime date;
                try
                {
                    date = DateTime.Parse("01-03-1991");
                }
                catch
                {
                    date = DateTime.Now;
                }

Less verbose way (using tryparse)

                DateTime date;
                if (!(DateTime.TryParse("01-03-1991", out date)))
                {
                    //hits this if the string doesn't parse into a date
                    date = DateTime.Now;
                }

What not to do…

A common mistake is to do this;

                DateTime date = DateTime.Now;
                DateTime.TryParse("01-03-1991", out date);

Assuming that the “tryparse” will do nothing to the output variable if it’s not a valid parse. This is not correct – if the string does not parse into a valid date, then the output variable will be initialized to its default value (in the case of a DateTime, this would be 01/01/0000).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s