C# 将字符串格式“yyyy-MM-ddTHH:mm:ss.fffZ”转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9152479/
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
Converting String Format "yyyy-MM-ddTHH:mm:ss.fffZ" to DateTime
提问by CalvinBlount
I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.
我知道这个问题已经被问到了很多不同的方式,我已经查看了所有这些问题,但似乎没有一个解决方案对我有用。所以,我希望你们能给我一个快速的帮助。
The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.
输入字符串是:“2000-01-01T12:00:000Z”。我需要获取该输入字符串并将其转换为 DateTime,以便将其存储在数据库中。
I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?
我一直在使用 ParseExact,但我不断收到无法识别的日期字符串异常。我哪里错了?
inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
采纳答案by SLaks
Your format string needs to exactly match the input.
您的格式字符串需要与输入完全匹配。
That includes the literal Tand Zcharacters.
这包括文字T和Z字符。
回答by Lucero
You don't specify the Tin the pattern.
您没有T在模式中指定。
That said, you may want to have a look at the XmlConvertclass, which provides the methods for converting this format.
也就是说,您可能想查看XmlConvert类,它提供了转换此格式的方法。
回答by dan04
You need to include \\Tand \\Zin your format string to match the literals Tand Z.
您需要在格式字符串中包含\\T和\\Z以匹配文字T和Z.
回答by inciph
You need to put single quotes around the T and Z:
你需要在 T 和 Z 周围加上单引号:
DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;
回答by Mohammad f
Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'
用 yyyy-MM-dd'T'HH:mm:ss.fff'Z'
The code is:
代码是:
public DateTime convertIsoToDateTime (string iso)
{
return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}

