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

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

DDD
DDDOriginal
2025-01-29 02:56:08943browse

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

Transforming DateTime Objects into ISO 8601 Strings

Standardized date and time representation is crucial when handling timestamps. The ISO 8601 format offers a precise and universally understood method. This guide details how to convert a DateTime object into an ISO 8601 string.

The "o" Formatter: The Recommended Approach

For optimal results, leverage the "o" formatter along with CultureInfo.InvariantCulture. This directly generates the round-trip ISO 8601 format, including the "Z" suffix indicating UTC time:

<code class="language-csharp">DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
// Example Output: 2023-03-08T17:36:28.9899302Z</code>

Customizing the Format

Should you need a specific ISO 8601 variation, utilize the ToString() method with a custom format string:

<code class="language-csharp">DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
// Example Output: 2023-03-08T17:36:28Z</code>

Important Consideration

Alternative methods may present inconsistencies, as noted in related discussions. Therefore, employing the "o" formatter or a defined custom format is strongly advised for reliable conversions.

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