Home >Backend Development >C++ >How to Parse Non-Standard DateTime Strings in C#?

How to Parse Non-Standard DateTime Strings in C#?

DDD
DDDOriginal
2025-02-02 03:16:09349browse

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:

  • Year, month, and day ("yyyy-MM-dd")
  • Hours, minutes, and seconds ("HH:mm:ss")
  • Milliseconds (including the comma and three digits ",fff")

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn