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

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

Susan Sarandon
Release: 2025-01-29 02:51:07
Original
699 people have browsed it

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

C# DateTime to ISO 8601 String Conversion

Efficiently exchanging date and time data requires a standardized format, and ISO 8601 ("yyyy-MM-ddTHH:mm:ssZ") is a popular choice. Here's how to achieve this conversion in C#:

One method involves custom date-time formatting:

<code class="language-csharp">DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz", CultureInfo.InvariantCulture);</code>
Copy after login

This produces an ISO 8601-like string (e.g., "2008-09-22T13:57:31.2311892-04:00"). For broader compatibility, however, the "round-trip" format is preferred:

<code class="language-csharp">DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);</code>
Copy after login

This yields a string like "2008-09-22T14:01:54.9571247Z", adhering to the ISO 8601 standard. A more concise format is also available:

<code class="language-csharp">DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);</code>
Copy after login

This offers a balance between precision and brevity for ISO 8601 representation. Choose the method that best suits your specific needs and compatibility requirements.

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