Thursday, September 19, 2024

Converting a Date to RFC822 for RSS Use

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:

DateTime.Now.ToString("r")

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

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

Response.Write(GetRFC822Date(DateTime.Now));

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.

Comments

Bookmark Murdok:

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.

Home


Related Articles

7 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

شما می خواهید یک بازی تخته قدیمی را از اتاق زیر شیروانی بیرون بیاورید.