解析字符串DateTime包含TimeZone信息 [英] Parse String DateTime containing TimeZone Info

查看:183
本文介绍了解析字符串DateTime包含TimeZone信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串值转换为datetime值,但是我收到一个System.FormatException错误。这是因为时区信息是日期字符串的一部分。有没有办法可以处理这种转换?

I am trying to convert a string value to a datetime value but am getting a System.FormatException error. This is because of the timezone info which is part of the date string. Is there any method which will be able to handle this conversion?

string date = "Wed, 04 Jan 2012 20:18:00 EST";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine(dt.ToString());


推荐答案

我不相信有任何自定义日期和时间格式字符串,它将解析或格式化时区缩写。你必须把它解散出来,解析本地的部分,从缩写中确定哪个时区是什么意思(祝你好运 - 它们是模糊的),然后将该时区应用到当地时间以获取UTC值(再次,这可能是模糊的)。

I don't believe there's any custom date and time format string which will parse or format a time zone abbreviation. You'll have to strip it out, parse the local part, work out which time zone is meant from the abbreviation (good luck with that - they're ambiguous) and then apply that time zone to the local time to get a UTC value (again, this can be ambiguous).

如果你可以控制格式,我会尽量避免包括时区信息,如果可以的话,或者包括一个偏移量,而不是一个时区,如果这一切都很重要(偏移量当然不会给出相同的信息),或者如果你真的需要时区,那么它就是一个明确的时区标识符。请注意,.NET使用Windows系统时区标识符;我自己的 Noda Time 项目使用了更广泛的 Olson / zoneinfo / tz 标识符,如果这对你有帮助。

If you're in control of the format at all, I would try to avoid including time zone information if you can, or include an offset rather than a time zone if that's all that's important (an offset doesn't give the same information of course), or an unambiguous time zone identifier if you really need the time zone. Note that .NET uses the Windows system time zone identifiers; my own Noda Time project uses the more widespread Olson / zoneinfo / tz identifiers, if that's helpful to you.

这篇关于解析字符串DateTime包含TimeZone信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆