« Creating Mixins with T4 in Visual Studio | Main | How to use UMDH to find native memory leaks »
April 14, 2009
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 at April 14, 2009 9:24 AM
Trackback Pings
TrackBack URL for this entry:
http://blog.logos.com/mt-cgi/mt-tb.cgi/285
Comments
The format string is a bit more legible without the single quotes; is there a reason not to omit them?
Posted by: Scott at April 17, 2009 10:28 AM
It should be safe to omit them; they’re only there to clearly delimit the literal parts. According to the latest documentation ( http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx), '-', 'T', and 'Z' have no meaning in DateTime formatting strings. ':' is “the time separator defined in the current DateTimeFormatInfo.TimeSeparator property”, but since we’re explicitly using CultureInfo.InvariantCulture, that should always produce a literal colon.
Posted by: Bradley Grainger
at April 17, 2009 10:50 AM