Convert String to DateTime in C#
Converting a string date to a DateTime object in C# can be a challenging task, especially when dealing with non-standard formats. One such format is "yyyyMMddHHmmss", which represents a date without separators.
Problem:
Consider the following string date:
20090530123001
This string was created using dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture). How can we convert it back into a proper DateTime object?
Solution:
The simplest approach is to use the DateTime.ParseExact method. This method takes three parameters:
For the given string, we can use the following code:
DateTime dateTime = DateTime.ParseExact("20090530123001", "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
This will successfully convert the string into a DateTime object.
Handling Invalid Formats:
However, if the string may not always be in the correct format, using ParseExact can result in a FormatException. To avoid this, you can use the DateTime.TryParseExact method instead. This method takes the same parameters as ParseExact but returns a boolean value indicating whether the conversion was successful.
The following code demonstrates how to use TryParseExact:
DateTime dateTime; if (DateTime.TryParseExact("20090530123001", "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { // Conversion successful } else { // Conversion failed }
The above is the detailed content of How to Convert a 'yyyyMMddHHmmss' String to a DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!