Useful C# extensions for working with ISO 8601 dates and strings

Hackered
Tuesday, August 12, 2014
by Sean McAlinden

I regularly work with ISO 8601 dates, especially when developing or testing REST API's so it makes sense to have some useful conversion extensions to hand.

The main format I have worked with recently is 2014-08-30T23:30:59Z.

Example Usage:

string isoDate = DateTime.UtcNow.ToIso8601Date();
DateTime date = isoDate.FromIso8601Date();

And here is the code:

///  /// DateTime Iso Extensions. /// 
public static class DateTimeIsoExtensions
{
    private const string DateTimeFormat = "{0}-{1}-{2}T{3}:{4}:{5}Z";

    ///  /// To the iso8601 date. /// 
    ///The date.
    /// 
    public static string ToIso8601Date(this DateTime date)
    {
        return string.Format(
            DateTimeFormat,
            date.Year,
            PadLeft(date.Month),
            PadLeft(date.Day),
            PadLeft(date.Hour),
            PadLeft(date.Minute),
            PadLeft(date.Second));
    }

    ///  /// Froms the iso8601 date. /// 
    ///The date.
    /// 
    public static DateTime FromIso8601Date(this string date)
    {
        return DateTime.ParseExact(date.Replace("T", " "), "u", CultureInfo.InvariantCulture);
    }

    private static string PadLeft(int number)
    {
        if (number < 10)
        {
            return string.Format("0{0}", number);
        }

        return number.ToString(CultureInfo.InvariantCulture);
    }
}