Format DateTime to ISO 8601

Format DateTime to ISO 8601

ISO 8601 is a general, international standard on how the complex representation of time stamps can be formulated in a general way - including the consideration of time formats, time zones and resolution.
Therefore, ISO 8601 is generally recommended for the exchange of time information, whether in databases, XML files or any other potential technology-neutral exchange format.

.NET does not have its own method for outputting ISO 8601, but it does have a standard-compliant option when formatting time objects: the o parameter.

To get a format like 2020-01-17T10:20:30.0000000Z you can this snippet:


    DateTime dat = new DateTime(2020, 1, 17, 10, 20, 30, DateTimeKind.Utc);
    Console.WriteLine("{0} ({1}) --> {0:o}", dat, dat.Kind);

My brain is unfortunately filled with a lot of nonsense, so that I keep forgetting that "o" is the appropriate format option. Therefore I wrote a little extension:

    public static string ToISO8601(this DateTimeOffset dt)
    {
        return dt.ToString("o");
    }
    public static string ToISO8601(this DateTime dt)
    {
        return dt.ToString("o");
    }

Finally you can just write

Console.WriteLine(dt.ToISO8601);