DateTime and ISO8601

The ISO 8601 standard for representing dates and times defines a (large) number of string formats for serializing dates. One of the more common formats in use (certainly here at Logos) uses the “extended format”, specifies the full date and time (but only in whole, not fractional, seconds) and always uses UTC. A string in this format looks like “2009-04-14T16:19:58Z”.

The standard date and time format strings for .NET don’t include a pattern that uses this precise format. The round-trip date/time pattern (specified by “o”) includes fractional seconds (e.g., “2009-04-14T16:19:58.0785018Z”), whereas the universal sortable date/time pattern (specified by “u”) has a space instead of a ‘T’ between the date and the time (e.g., “2009-04-14 16:19:58Z”).

We wrote the following utility methods to parse and render DateTimes in our preferred format:

/// <summary>

/// Provides methods for manipulating dates.

/// </summary>

public static class DateTimeUtility
{
    /// <summary>

    /// Converts the specified ISO 8601 representation of a date and time

    /// to its DateTime equivalent.

    /// </summary>

    /// <param name="value">The ISO 8601 string representation to parse.</param>

    /// <returns>The DateTime equivalent.</returns>

    public static DateTime ParseIso8601(string value)
    {
        return DateTime.ParseExact(value,
            Iso8601Format, CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
    }

    /// <summary>

    /// Formats the date in the standard ISO 8601 format.

    /// </summary>

    /// <param name="value">The date to format.</param>

    /// <returns>The formatted date.</returns>

    public static string ToIso8601(this DateTime value)
    {
        return value.ToUniversalTime().ToString(Iso8601Format, CultureInfo.InvariantCulture);
    }

    /// <summary>

    /// The ISO 8601 format string.

    /// </summary>

    public const string Iso8601Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
}

Posted by Bradley Grainger on April 14, 2009