HOWTO: [DotNet] Convert a DateTime structure to a Rfc822 mime conform string?

If you have to deal with MIME you'll have to interpret date information.

Some programmers argue, that the DotNet framework, should support the RFc822 date format out of the box.
Others say,  'no, you need not, because RFC1123  has already been implemented which goes as "Sun, 04 Dec 2005 20:57:57 GMT" for instance'.

I do not agree with this completely. First because sometimes, you might want to be able to detect the timezone difference between clients. If you have a GMT notation, you have the correct worldtime in sync, but you won't see a difference.

Second, if the RFC or API recommends a RFC822 it is a error to assume that the runtime or their runtime, automatically will deal with rfc1123 as well (it is in many situations).

So here is a way to format your string into rfc822. I did not pack it into a handy class or something. Just use the idea. You could make it detect and accept rfc822 and rfc1123 as well!

    // the (UTC) suffix  is optional. You can leave it out.

    DateTime dt = DateTime.Now;

    string Rfc822DateTime = dt.ToString(@"ddd, dd MMM yyyy HH:mm:ss zzzz (\U\T\C)", System.Globalization.DateTimeFormatInfo.InvariantInfo);

    // remove the time separator in the timezone because zzzz will produce +01:00 for instance

    Rfc822DateTime = Rfc822DateTime.Remove(Rfc822DateTime.LastIndexOf(':'), 1);

 

    // for the sake of completeness I want to state that formatting as an RFc1123 string is as simple as formatting using a predefined mask that is .ToString("r").

    // and do not forget the ToUniversalTime() method or otherwise, the time string is still a local time!

    string rfc1123DateTime = dt.ToUniversalTime().ToString("r"); 

 

    // and convert the rfc822 formatted date back 

    if (Rfc822DateTime.EndsWith("(UTC)"))

        Rfc822DateTime = Rfc822DateTime.Substring(0, Rfc822DateTime.Length - 6);

 

    DateTime rfc822Parse = DateTime.ParseExact(Rfc822DateTime, @"ddd, dd MMM yyyy HH:mm:ss zzzz", System.Globalization.DateTimeFormatInfo.InvariantInfo);

    // rfc822Parse equals e.g.: "Mon, 15 May 2006 08:31:40 GMT"

    // rfc1123DateTime equals eg.: "Mon, 15 May 2006 10:31:40 +0200"

   

    // converting from string to datetime also requires us to convert from UTC to Local manually

    DateTime rfc1123Parse = DateTime.ParseExact(rfc1123DateTime, "r", System.Globalization.DateTimeFormatInfo.InvariantInfo).ToLocalTime();

    if (rfc822Parse != rfc1123Parse)

        throw new FormatException("rfc822Parse and rfc1123Parse should be equal!");

blog comments powered by Disqus