在 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);
I am trying to parse dates in RFC1123 format (Thu, 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过类似的操作:
我还没有测试过(稍后会测试)...但我相信这会为您做。
编辑:问题似乎在于 RFC1123 规定时区应始终为 GMT...这就是为什么 r 或 R 不适合您的格式。问题是EST。上面的模式考虑了 EST,但它是静态的,因此如果您有任何其他时区,您可能会遇到麻烦。最好的解决方案是采用 RFC1123 标准并转到 GMT,它应该可以解决您的问题。如果你不能,请告诉我我可能有解决方案。
编辑2:这不是一个完整的解决方案,但它的作用是隔离时区并仍然允许您解析它。该代码不知道它所呈现的时区,但您可以向它抛出任何时区缩写,它会解析时间。如果您想转换为 GMT,然后使用 r 或 R,您可以获取正则表达式匹配的结果,将其放在查找表中(以查看该时区缩写的时间偏移量),然后将时间转换为 GMT 并从那里解析。这将是一个很好的解决方案,但需要做更多的工作。代码如下:
如果您想将其转换为时区转换器,这里有一个 UTC 偏移量列表:
带有 UTC 偏移量的时区缩写
Have you tried something like:
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:
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
我遇到了这个问题,正在寻找同一问题的解决方案。真是不可思议,12年来运行时都没有解决方案
这是我的解决方案:
I reached this question looking for a solution to the same problem. It's really incredible that in 12 years no solution in runtime
This is my solution: