Home >Backend Development >C++ >How to Convert an ISO 8601 String to a .NET DateTime Object?

How to Convert an ISO 8601 String to a .NET DateTime Object?

Barbara Streisand
Barbara StreisandOriginal
2025-01-17 02:22:09862browse

How to Convert an ISO 8601 String to a .NET DateTime Object?

Convert ISO 8601 String to .NET DateTime

Introduction

Transforming a DateTime object to ISO 8601 format is a common task, but its conversion back to DateTime is less documented in C#. This article demonstrates how to efficiently parse an ISO 8601 string into a DateTime object.

Parsing ISO 8601 String

To create a DateTime object from an ISO 8601 string, utilize DateTime.Parse() with the following considerations:

  • For timestamps without a time zone offset (e.g., "2010-08-20T15:00:00"), use the following code:
DateTime d1 = DateTime.Parse("2010-08-20T15:00:00");
  • For timestamps with a 'Z' time zone offset (e.g., "2010-08-20T15:00:00Z"), use DateTimeStyles.RoundtripKind:
DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

Example

Consider the ISO 8601 string "2010-08-20T15:00:00Z". To convert it to a DateTime object using RoundtripKind:

DateTime d3 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This approach correctly handles the time zone information and accurately represents the DateTime value.

The above is the detailed content of How to Convert an ISO 8601 String to a .NET DateTime Object?. 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