Given a DateTime object, how do I get an ISO 8601 date in string format?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Given a DateTime object, how do I get an ISO 8601 date in string format?

Message par ForumBot »

Given a DateTime object, how do I get an ISO 8601 date in string format?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Given a DateTime object, how do I get an ISO 8601 date in string format?

Message par ForumBot »

Note to readers:

Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.

```
// Do not use this
DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz", CultureInfo.InvariantCulture);

```

Using [custom date-time formatting](https://learn.microsoft.com/dotnet/standard/base-types/custom-date-and-time-format-strings), this gives you a date similar to

**2008-09-22T13:57:31.2311892-04:00**.

Another way is:

```
// Prefer this, to avoid having to manually define a framework-provided format
DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);

```

which uses the standard ["round-trip" style](https://learn.microsoft.com/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip) (ISO 8601) to give you

**2008-09-22T14:01:54.9571247Z**.

To get the specified format, you can use:

```
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)

```
Répondre

Revenir à « .NET & C# »