How to Convert String to DateTime in C#

How to Convert String to DateTime in C#. In this C# example, Let’s see How to Convert String to Date and Time in C# with different formats.

In .Net, you can work with date and time easily with the DateTime class. You can use the methods like Convert.ToDateTime(String), DateTime.Parse() and DateTime.ParseExact() methods for converting a string-based date to a System.DateTime object.

Convert.ToDateTime(String)

This method will convert the specified string representation of a date and time to an equivalent date and time value.

string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + "  " + oDate.Year );

DateTime.Parse()

DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among the text.

string iDate = "2005-05-05";
DateTime oDate = DateTime.Parse(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + "  " + oDate.Year);

DateTime.ParseExact()

In C#, the ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.

string iString = "2005-05-05 22:12 PM";
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
MessageBox.Show(oDate.ToString());

DateTime.TryParse method

DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style and returns a value that indicates whether the conversion succeeded.

public static bool TryParse(
 string s,
 out DateTime result
)

This method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails. Also, this method tries to ignore unrecognized data, if possible and fills in the missing month, day, and year information with the current date. The TryParse method is culture-dependent so be very careful if you decide to use it.

C# Program that uses DateTime.Parse function

using System;
 
public class Example
{
    public static void Main()
    {
        string date = "28/12/2019";
 
        try {
            DateTime dateTime = DateTime.Parse(date);
            Console.WriteLine("The specified date is valid: " + dateTime);
        }
        catch (FormatException) {
            Console.WriteLine("Unable to parse the specified date");
        }
    }
}
Output: The specified date is valid: 28-12-2019 12.00.00 AM

In this way, we learn How to Convert String to DateTime in C#.