Formatting a DateTime per RFC822

There doesn't seem to a be a built-in mechanism to format a DateTime instance according to RFC #822.

            /// <summary>
            /// Returns a RFC822-compliant string representing a DateTime instance.
            /// </summary>
            /// <param name="datetime">The DateTime instance to be formatted.</param>
            /// <returns>The specified datetime formatted as a RFC822 datetime string.</returns>
            /// <exception cref="System.ArgumentNullException">The parameter datetime is null.</exception>
            public static string AsRFC822String(this DateTime datetime)
            {
                if (datetime == null)
                {
                    throw new ArgumentNullException("datetime");
                }
            
                int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
                string timeZone = "+" + offset.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
                if (offset < 0)
                {
                    int i = offset * -1;
                    timeZone = "-" + i.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
                }
                
                return datetime.ToString(
                    "ddd, dd MMM yyyy HH:mm:ss " + timeZone.PadRight(5, '0'),
                    CultureInfo.InvariantCulture);
            }
        


Tags

  • .NET

Revisions

  • 8/16/2012 - Article published.