Converting a Date to RFC822 for RSS Use

    November 20, 2006

I wrote a new dynamic RSS feed for a little project called Little Helper. It all works fine, but when I tried to validate it using FeedValidator, the pubDate was invalid.

The validator told me that the date was not proper formatted using the RFC822 standard which looks something like this:

Wed, 27 Sep 2006 21:36:45 +0200.

Ok, that’s no problem right? Just format the DateTime correctly and you’re ready to go. Wrong!

This is what happens if you try to do just that:


The output of that is:

Wed, 27 Sep 2006 21:49:19 GMT

GMT is an acceptable value for RFC822, but not for my location which should be +0200. It fails on all the machines I tried it on. If I then try to write the format string manually like this, it still doesn’t work.

DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzzz")

The output of that is:

Wed, 27 Sep 2006 21:36:45 +02:00

It is almost correct, but the time zone is not formatted correctly. After searching the web, it became clear that .NET does not let you format the DateTime to the RFC822 by its standard formatters. So, I had to write a little method that did just that.

/// <summary>

/// Converts a regular DateTime to a RFC822 date string.

/// </summary>

/// <returns>The specified date formatted as a RFC822 date string.</returns>

private static string GetRFC822Date(DateTime date)


   int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;

   string timeZone = "+" + offset.ToString().PadLeft(2, '0');

   if (offset < 0)    {    int i = offset * -1;    timeZone = "-" + i.ToString().PadLeft(2, '0');    }    return date.ToString("ddd, dd MMM yyyy HH:mm:ss " + timeZone.PadRight(5, '0')); }

Just give it a DateTime and it will return a properly formatted RFC822 string that will validate.


Note, that the RSS feed probably works fine without using a method like this, even though the FeedValidator doesn't agree. At the end of the day, the feed validated.


Bookmark WebProNews:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.