Parsing/Converting String as Date Time using C#

In this blog, we are going to parse the string to specific Date Time data Type.

Usage:

DateTime a3 = TryParseDateTime("31/5/2012", DateTime.MinValue);//TRUE
DateTime b3 = TryParseDateTime("05/32/2012", DateTime.MinValue);//FALSE

Response.Write(string.Format("A:{0},B:{1}", a3.ToString("dd/MM/yyyy"),

b3.ToString("dd/MM/yyyy")) + "<br/>");


Output:

A:31/05/2012,B:01/01/0001


Method1: DateTime.TryParse

Best to use if there is uncertain about the input string.

        /// <summary>
        /// Note it takes your System dateTime format like d/M/yyyy etc.
        /// It wont throw error. Instead it gives the ifFail value if error occurs
        /// </summary>
        public DateTime TryParseDateTime(string input, DateTime ifFail)

        {
            DateTime output;

            if (DateTime.TryParse(input, out output))
            {
                output = output;
            }
            else
            {
                output = ifFail;
            }

            return output;
        }

Method 2: DateTime.Parse

If you sure about the input string going to be valid, then go for this method.

/// <summary>
        /// Parses the string as DateTime. But if datetime string is invalid, then it throws error
        /// </summary>
        public DateTime ParseDateTime(string input)
        {
            return DateTime.Parse(input);
        }

Thanks for reading this article. Have a nice day.

Ebook Download
View all
Learn
View all