Home >Backend Development >C++ >How to Reliably Convert a String to a DateTime Object in C#?
Converting a String to a DateTime in C#
In C#, formatting a DateTime object using ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) results in a string representation of the date and time. However, converting this string back into a DateTime object can be tricky.
One common approach, Convert.ToDateTime(...), may fail due to a format mismatch. To address this, consider using DateTime.ParseExact:
DateTime dateTime = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
This method parses the string based on the specified format and returns a DateTime object.
Alternatively, for non-exact matches, employ DateTime.TryParseExact:
DateTime dateTime; DateTime.TryParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
This method returns true if the conversion succeeds, and false otherwise. The output dateTime variable will contain the parsed DateTime object if successful.
The above is the detailed content of How to Reliably Convert a String to a DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!