Home > Backend Development > C++ > How Do I Convert an ISO 8601 String to a C# DateTime Object?

How Do I Convert an ISO 8601 String to a C# DateTime Object?

Susan Sarandon
Release: 2025-01-17 02:39:09
Original
438 people have browsed it

How Do I Convert an ISO 8601 String to a C# DateTime Object?

Convert ISO 8601 format to .NET DateTime object

Converting formatted date and time strings to DateTime objects is very easy in C#. Consider ISO 8601 format:

<code>2010-08-20T15:00:00Z</code>
Copy after login

Standard Method

This conversion can be done using the DateTime.Parse() method. However, it requires using the DateTimeStyles enumeration to specify the expected format:

<code>DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);</code>
Copy after login

By setting the RoundtripKind value, the parser will automatically interpret "Z" as the Zulu (UTC) time zone.

Custom parsing (not recommended)

While manual parsing is possible, it is generally not recommended as it is error-prone. Breaking the ISO 8601 string into its individual components would be a tedious task.

Example output

Using the provided solution, the following output will be generated:

<code>2010-08-20 15:00:00</code>
Copy after login

The above is the detailed content of How Do I Convert an ISO 8601 String to a C# DateTime Object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template