加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:32:03 所属栏目:百科 来源:网络整理
导读:我试图解析RFC1123格式的日期(星期四,2010年1月21日17:47:00 EST). 这是我尝试但没有工作: DateTime Date = DateTime.Parse(dt);DateTime Date = DateTime.ParseExact(dt,"r",null); 你能帮我一下吗? 谢谢, ruby:) 解决方法 你有没有尝试像: string dateS
我试图解析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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读