This post will discuss how to convert the specified string representation of a date and time format to its DateTime equivalent in C#.

1. Using DateTime.Parse() method

To convert a string representation of a date and time to the DateTime object, use the DateTime.Parse() method. The return value of this method indicates whether the conversion succeeded. The following example validates a date and time string by converting it into a DateTime object using the Parse() method.

Download  Run Code

2. Using DateTime.TryParse() method

We can avoid the try-catch block using the DateTime.TryParse() method. The method returns a boolean value to indicate whether the conversion is succeeded or not.

Download  Run Code

3. Using DateTime.ParseExact() method

Alternatively, we can also use DateTime.ParseExact() method to convert the specified string to its equivalent DateTime representation. This also allows us to pass the required format of the string and culture-specific format information about the string. If the format of the string representation doesn’t match with the specified format, an exception will be thrown.

Download  Run Code

4. Using DateTime.TryParseExact() method

We can avoid the try-catch block using the DateTime.TryParseExact() method. This method returns true if the string is successfully converted to DateTime and false otherwise.

Download  Run Code

That’s all about converting a String to DateTime in C#.