将 ISO 8601 解析为 C# DateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19420937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:56:43  来源:igfitidea点击:

Parse ISO 8601 to C# DateTime

c#parsingdatetimeisoiso8601

提问by Daniel M

I got a bunch of DateTime-Strings I want to parse into a c# DateTime.

我有一堆 DateTime-Strings 我想解析成 ac#DateTime。

2009-06-18 02:10:31.296761+00
2009-06-18 02:13:34.049145+00
2009-01-06 23:52:21.510121+00
2009-06-18 02:17:57.268252+00
2010-01-22 03:31:26.512496+00
2009-06-18 01:32:37.930961+00

I'm currently trying to get the DateTime-Object with the following line of code:

我目前正在尝试使用以下代码行获取 DateTime-Object:

DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.None);

But I'm always getting a System.FormatException.

但我总是收到 System.FormatException。

采纳答案by Panagiotis Kanavos

You don't have to do anything fancy, a simple DateTime.Parseworks:

你不必做任何花哨的事情,一个简单的DateTime.Parse作品:

DateTime myDate1 = DateTime.Parse("2009-06-18 02:10:31.296761+00");
DateTime myDate2 = DateTime.Parse("2009-06-18 02:10:31.296761+03");

Both lines will work and the resulting dates will take the offset into account.

两条线都可以工作,结果日期将考虑偏移量。

The reason this works is that the format you supplied is one of the standard datetime formats, specifically the universal sortable format, not ISO 8601.

这样做的原因是您提供的格式是标准日期时间格式之一,特别是通用可排序格式,而不是 ISO 8601。

ISO 8601 corresponds to the roundtripformat and uses 'T' instead of ' ' to separate date from time.

ISO 8601 对应于往返格式并使用“T”而不是“ ”来分隔日期和时间。