Different date conversion from string to date in C#


In the article, we will learn about various date conversion method that converts date type String to data type date.

To better understand this tutorial, you should be knowledgeable in  following C# programming topic:

Sting to Date conversion is one of the most used transformations in software development. For some reasons, software developers store Date data in a String format when using databases as data storage. Also, data stored in flat files are always in string data type. Comparing, manipulation, and retrieval of the Date data will require converting it into Date Data Type.

Here is a list of methods that can convert String data to Date data.

DateTime.Parse converts a string to a DateTime equivalent. The string must represent a date and time; otherwise, it will throw an exception.

Example:

            string strDate = "02/02/2018";
            Console.WriteLine(DateTime.Parse(strDate).ToString());

Output:

2/2/2018 12:00:00 AM

Now let’s try to convert an invalid string Date:

            string strDate = "01/01/ABC2018";
            Console.WriteLine(DateTime.Parse(strDate).ToString());

Output

The string was not recognized as a valid DateTime. There is an unknown word starting at index 6.

DateTime.ParseExact converts a string of a date and time to a DateTime equivalent using a specific format and culture-specific format

Example:

DateTime Date;
string format = "M/d/yyyy h:mm tt";
string dateString = "2/1/2018 6:36 PM";
Date = DateTime.ParseExact(dateString, format,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.Write(Date.ToString());

Output:

2/1/2018 6:36:00 PM

DateTime.TryParse converts a string of a date and time to a DateTime equivalent and returns a value which indicated whether the conversation has succeeded or not.

Example:

                string strDate = "2018-02-02";
                DateTime dateTime;
                if (DateTime.TryParse(strDate, out dateTime))
                {
                    Console.WriteLine(dateTime);
                }

Output:

2/2/2018 12:00:00 AM

Now let’s try to pass an invalid date:

                string strDate = "abc2018-02-02";
                DateTime dateTime;
                if (DateTime.TryParse(strDate, out dateTime))
                {
                    Console.WriteLine(dateTime);
                    txt.Text = dateTime.ToString();
                }
                else
                {
                    txt.Text = "invalid date input";
                }

Output:

invalid date input

Related Articles:

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply