How to parse and generate DateTime objects in ISO 8601 format

The format you’re describing is ISO 8601.

Since you’re working with timestamps that inclulde a time zone component, I’d strongly recommend using DateTimeOffset instead of DateTime. It makes things so much easier!

To create a DateTimeOffset for a given date, time, and time zone offset, use this syntax:

var date = new DateTimeOffset(2016, 3, 29, 12, 20, 35, 93, TimeSpan.FromHours(-5));
// March 29, 2016 at 12:20:35.93 GMT-5

This code will format a DateTimeOffset as ISO 8601:

public static string FormatIso8601(DateTimeOffset dto)
{
    string format = dto.Offset == TimeSpan.Zero
        ? "yyyy-MM-ddTHH:mm:ss.fffZ"
        : "yyyy-MM-ddTHH:mm:ss.fffzzz";

    return dto.ToString(format, CultureInfo.InvariantCulture);
}

And, to parse a string back to a DateTimeOffset:

public static DateTimeOffset ParseIso8601(string iso8601String)
{
    return DateTimeOffset.ParseExact(
        iso8601String,
        new string[] { "yyyy-MM-dd'T'HH:mm:ss.FFFK" },
        CultureInfo.InvariantCulture,
        DateTimeStyles.None);
}

If you must get back to a DateTime you can get this from the DateTimeOffset.UtcDateTime property.

Leave a Comment