How to Parse a String to a DateTime Object in C# using TryParseExact

Learn how to use the TryParseExact method in C# to parse a string in the format of “27-Mar-2023” to a DateTime object. This tutorial covers the syntax of the method and provides a code example for you to follow. Improve your C# programming skills today!

To parse a string in the format of “27-Mar-2023” to a DateTime object in C# using DateTime.TryParseExact, you can use the following code:

string dateString = "27-Mar-2023";
DateTime result;
if (DateTime.TryParseExact(dateString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    // Parsing succeeded, result variable now contains the parsed DateTime object
    // Parsing failed

In this code, we first define the input string dateString as “27-Mar-2023”. Then, we use DateTime.TryParseExact to try to parse the string into a DateTime object. The format string “dd-MMM-yyyy” specifies the pattern of the input string, where “dd” represents the day of the month, “MMM” represents the abbreviated month name (e.g. “Mar”), and “yyyy” represents the year. We also specify the CultureInfo.InvariantCulture to indicate that we’re using a culture-independent format, and DateTimeStyles.None to indicate that we don’t want to use any additional parsing options.

If the parsing succeeds, the result variable will contain the parsed DateTime object. If the parsing fails, the TryParseExact method will return false, and we can handle the error accordingly.

Similar Posts