如何从 ISO 8601 格式创建 .NET DateTime
我找到了如何将 DateTime 转换为 ISO 8601 格式,但没有介绍如何操作C# 中则相反。
我有 2010-08-20T15:00:00Z
,我想将其转换为 DateTime
对象。
我可以自己分离字符串的各个部分,但这对于已经成为国际标准的东西来说似乎需要大量工作。
I've found how to turn a DateTime into an ISO 8601 format, but nothing on how to do the reverse in C#.
I have 2010-08-20T15:00:00Z
, and I want to turn it into a DateTime
object.
I could separate the parts of the string myself, but that seems like a lot of work for something that is already an international standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
此解决方案利用 DateTimeStyles 枚举,并且它也适用于 Z这
完美地打印了解决方案。
This solution makes use of the DateTimeStyles enumeration, and it also works with Z.
This prints the solution perfectly.
尽管 MSDN 说“s”和“o”格式反映了标准,但它们似乎只能解析标准的有限子集。特别是如果字符串包含时区规范,则会出现问题。 (它对于基本 ISO8601 格式或降低精度的格式都不起作用 - 但这不完全是您的情况。)这就是为什么我在解析 ISO8601 时使用自定义格式字符串。目前我的首选片段是:
如果您不介意解析无 TZ 的字符串(我愿意),则可以添加“s”行以大大扩展所覆盖的格式更改的数量。
Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:
If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.
这是一个更适合我的版本(LINQPad 版本)
:
Here is one that works better for me (LINQPad version):
produces
为了让
TryParseExact
正常工作,精确匹配 ISO 字符串的格式似乎很重要。我想 Exact 就是 Exact,这个答案对大多数人来说都是显而易见的,但无论如何......就我而言,Reb.Cabin 的答案不起作用,因为我的输入与下面的“值”略有不同。
值:
2012-08-10T14:00:00.000Z
其中有一些额外的 000 表示毫秒,并且可能还有更多。
但是,如果我将一些
.fff
添加到如下所示的格式中,一切都很好。格式字符串:
@"yyyy-MM-dd\THH:mm:ss.fff\Z"
在 VS2010 立即窗口中:
true
您可能必须使用
DateTimeStyles.AssumeLocal
作为好吧,取决于你的时间在哪个区域......It seems important to exactly match the format of the ISO string for
TryParseExact
to work. I guess Exact is Exact and this answer is obvious to most but anyway...In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.
Value:
2012-08-10T14:00:00.000Z
There are some extra 000's in there for milliseconds and there may be more.
However if I add some
.fff
to the format as shown below, all is fine.Format String:
@"yyyy-MM-dd\THH:mm:ss.fff\Z"
In VS2010 Immediate Window:
true
You may have to use
DateTimeStyles.AssumeLocal
as well depending upon what zone your time is for...这在 LINQPad4 中工作得很好:
This works fine in LINQPad4:
DateTime.ParseExact(...)
允许您告诉解析器每个字符代表什么。DateTime.ParseExact(...)
allows you to tell the parser what each character represents.