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

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

DDD
Release: 2025-02-02 03:16:09
Original
404 people have browsed it

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:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template