微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C#,.Net 4.0中解析RFC1123格式的日期

我试图解析RFC1123格式的日期(星期四,2010年1月21日17:47:00 EST).

这是我尝试但没有工作:

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

你能帮我一下吗?

谢谢,
ruby:)

解决方法

你有没有尝试像:
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());

我还没有测试(会在一会儿)…但我相信会为你做的.

编辑:似乎问题是RFC1123规定时区应该始终是GMT …这就是为什么r或r不能作为你的格式.问题是EST.上面的模式描述了EST,但它是静态的,所以如果你有任何其他时区,你可能会遇到麻烦.最好的解决方案是使用RFC1123标准,并转到GMT,它应该可以解决你的问题.如果你不能,让我知道我可能会有一个解决方案.

编辑2:这不是一个完整的解决方案,但它是如何隔离时区,仍然允许你解析它.该代码不知道它正在呈现的时区,但是您可以在其上抛出任何时区缩写,它将解析时间.如果要转换为GMT,然后使用r或R,则可以使用正则表达式匹配的结果,将其放在查找表上(查看该时区缩写的时间偏移量),然后将时间转换为GMT和从那里解析这将是一个很好的解决方案,但更多的工作.以下是代码

string dateString,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,provider);
    Console.WriteLine("Timezone format is: {0}",format);
    Console.WriteLine("{0} converts to {1}.",result.ToString());
}
catch (FormatException)
{
    Console.WriteLine("{0} is not in the correct format.",dateString);
}

    Console.ReadLine();

如果你想把它变成一个时区转换器,这是一个UTC偏移列表:

Timezone Abbreviations with UTC offsets

原文地址:https://www.jb51.cc/csharp/95364.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐