Home >Backend Development >C++ >How to Parse Non-Standard DateTime Strings in C#?
Handling Irregular Date and Time Strings in C#
Many applications encounter date and time strings that deviate from standard formats. For example, "2009-05-08 14:40:52,531" is not a readily parsable DateTime string using default methods.
The Solution: Custom Date/Time Formatting
The key to parsing these non-standard strings is using C#'s DateTime.ParseExact
method with a custom format string. This string precisely mirrors the structure of your irregular date/time string.
In the example string "2009-05-08 14:40:52,531", we need to account for:
C# Code Example
Here's how to parse the string using DateTime.ParseExact
:
<code class="language-csharp">DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);</code>
System.Globalization.CultureInfo.InvariantCulture
ensures consistent parsing regardless of regional settings. This approach guarantees reliable conversion of non-standard date and time strings into usable DateTime
objects.
The above is the detailed content of How to Parse Non-Standard DateTime Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!