Converting DateTime Objects to ISO 8601 Format Strings
Working with dates and times often requires consistent and portable date representations, and the ISO 8601 standard is ideal for this. This article shows you how to reliably convert .NET DateTime objects into ISO 8601 strings.
While you could use ToString()
with a custom format string, this is prone to errors. A more robust solution leverages the framework's built-in "round-trip" format specifier ("o"
). This ensures compliance with the ISO 8601 standard.
Here's how to achieve this using UTC time:
<code class="language-csharp">DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);</code>
This produces a string in the format yyyy-MM-ddTHH:mm:ss.fffffffZ
. Note the trailing 'Z' indicating UTC.
If you require a slightly different ISO 8601 format, such as yyyy-MM-ddTHH:mm:ssZ
, you can specify a custom format:
<code class="language-csharp">DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);</code>
Remember to use CultureInfo.InvariantCulture
to avoid locale-specific formatting issues. These methods provide a simple and reliable way to convert DateTime objects into the desired ISO 8601 date string format for various applications.
The above is the detailed content of How to Efficiently Convert DateTime Objects to ISO 8601 Date Strings?. For more information, please follow other related articles on the PHP Chinese website!