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

Try this:

  DateTime today = DateTime.Now;
  String rfc822 = today.ToString("r");
  Console.WriteLine("RFC-822 date: {0}", rfc822);

  DateTime parsedRFC822 = DateTime.Parse(rfc822);
  Console.WriteLine("Date: {0}", parsedRFC822);

The “r” format specifier passed into DateTime’s ToString() method actually yields an RFC-1123-formatted datetime string, but passes as an RFC-822 date as well, based on reading the specification found at http://www.w3.org/Protocols/rfc822/#z28. I’ve used this method in creating RSS feeds, and they pass validation based on the validator available at http://validator.w3.org/feed/check.cgi.

The downside is that, in the conversion, it converts the datetime to GMT. To convert back to local time you would need to apply your local timezone offset. For that, you might use the TimeZone class to get your current timezone offset, and replace “GMT” with a timezone offset string:

TimeZone tz = TimeZone.CurrentTimeZone;

String offset = tz.GetUtcOffset().ToString();
// My locale is Mountain time; offset is set to "-07:00:00"
// if local time is behind utc time, offset should start with "-".
// otherwise, add a plus sign to the beginning of the string.
if (!offset.StartsWith("-"))
  offset = "+" + offset; // Add a (+) if it's a UTC+ timezone
offset = offset.Substring(0,6); // only want the first 6 chars.
offset = offset.Replace(":", ""); // remove colons.
// offset now looks something like "-0700".
rfc822 = rfc822.Replace("GMT", offset);
// The rfc822 string can now be parsed back to a DateTime object,
// with the local time accounted for.
DateTime new = DateTime.Parse(rfc822);

Leave a Comment