by Jim
Nov 11, 2007 12:38 PM
I'm using Peter Huber's Pop3MimeClient code to check emails, and needed a way to parse the date string from the email header into a .NET DateTime object. The date format is defined in the email standard RFC822.
This is the code I wound up with:
// Date string in the header looks like this:
// Sun, 23 Sep 2007 09:24:59 -0500 (CDT)
// Remove the parenthetical reference to the time zone; this is redundant since
// we have the offset and time zone can't be represented in the format string
string sentString = Headers["Date"];
sentString = System.Text.RegularExpressions.Regex.Replace(sentString,
"\\([a-zA-Z]*\\)", "");
return DateTime.ParseExact(sentString.Trim(), new string[] {
"ddd, dd MMM yyyy HH:mm:ss zzzzz",
"ddd, d MMM yyyy HH:mm:ss zzzzz"},
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AllowWhiteSpaces);
I used a regex to remove the (CDT) from the end of the string because there doesn't appear to be a wildcard character available for the DateTime format specifier. The two format strings are necessary because "dd" doesn't accept days less than ten.