开发者

Parsing RFC1123 formatted dates in C#, .Net 4.0

开发者 https://www.devze.com 2022-12-25 22:56 出处:网络
I am trying to parse dates in RFC1123 format (T开发者_JAVA技巧hu, 21 Jan 2010 17:47:00 EST). Here is what I tried but none worked:

I am trying to parse dates in RFC1123 format (T开发者_JAVA技巧hu, 21 Jan 2010 17:47:00 EST).

Here is what I tried but none worked:

DateTime Date = DateTime.Parse(dt);
DateTime Date = DateTime.ParseExact(dt, "r", null);


Have you tried something like:

string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

dateString = "Thu, 21 Jan 2010 17:47:00 EST";
format = "ddd, dd MMM yyyy hh:mm:ss EST";

result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());

I haven't tested it yet (will in a few moments)... but I believe that will do it for you.

Edit: It seems that the problem is that RFC1123 states that the timezone should always be GMT... which is why r or R did not work as a format for you. The problem is the EST. The pattern above accounts for EST, but it is static so if you have any other timezone you might be in trouble. The best solution would be to go with the RFC1123 standard and go to GMT and it should solve your problem. If you can't, let me know I might have a solution.

Edit 2: This is not a complete solution but what it does it isolates the timezone and still allows you to parse it. The code doesn't know the timezone that it is being presented with but you can throw any timezone abbreviation at it and it will parse the time. If you want to convert to GMT and then use r or R you can take the result of the regex match, put it against a lookup table (to see what the time offset it for that timezone abbreviation), then convert the time to GMT and parse from there. That would be a good solution but a little more work. Here's the code:

string dateString, format, pattern, tz;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
pattern = @"[a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ (?<timezone>[a-zA-Z]+)";
dateString = "Thu, 21 Jan 2010 17:47:00 EST";

Regex findTz = new Regex(pattern, RegexOptions.Compiled);

tz = findTz.Match(dateString).Result("${timezone}");

format = "ddd, dd MMM yyyy HH:mm:ss " + tz;

try
{
    result = DateTime.ParseExact(dateString, format, provider);
    Console.WriteLine("Timezone format is: {0}", format);
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
    Console.WriteLine("{0} is not in the correct format.", dateString);
}

    Console.ReadLine();

Here is a list of UTC offsets for you if you would like to turn this into a timezone converter:

Timezone Abbreviations with UTC offsets

0

精彩评论

暂无评论...
验证码 换一张
取 消