Alex Rivera | Logout

How do I parse and convert DateTime’s to the RFC 822 date-time format?

Asked 2008-11-12T18:04:01.437
41

How do I convert a DateTime structure to its equivalent RFC 822 date-time formatted string representation and parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the RSS Syndication Format.

Edit
Report

1 Answer

1

Based on the answer of Kirk Liemohn, I used this method with success:

private DateTimeOffset? ParseDate(string date)
    {
        const string FORMAT = "ddd, d MMM yyyy HH:mm:ss zzz";
        const string FORMAT2 = "ddd, dd MMM yyyy HH:mm:ss zzz";
        const string FORMAT3 = "dd MMM yyyy HH:mm:ss zzz";
        const string FORMAT4 = "d MMM yyyy HH:mm:ss zzz";
        DateTimeOffset d;
        if (DateTimeOffset.TryParseExact(date, new string[] { FORMAT, FORMAT2, FORMAT3, FORMAT4 }, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out d))
            return d;
        return null;
    }

Example:

DateTimeOffset? date = ParseDate("Thu, 5 Apr 2012 23:47:37 +0200");
Console.WriteLine(date.ToString());
// => 05/04/2012 23:47:37 +02:00

It does not respect full spec of RFC but it works for my use cases.

Specifically, it does not work with timezone express like : "GMT", "CST", etc. (see "zone" in RFC822 Section 5.1). See the better answer of Oleksandr Pshenychnyy.

answered 2012-05-03T07:31:40.207

Your Answer