为什么不能DateTime.ParseExact()解析" 9/1/2009年"使用" M / D / YYYY" [英] Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"
问题描述
我有一个字符串,它看起来像这样:9/1/2009。我想(用C#)将其转换为一个DateTime对象。
I have a string that looks like this: "9/1/2009". I want to convert it to a DateTime object (using C#).
本作品:
DateTime.Parse("9/1/2009", new CultureInfo("en-US"));
但我不明白为什么这不起作用:
But I don't understand why this doesn't work:
DateTime.ParseExact("9/1/2009", "M/d/yyyy", null);
有在日期(如九)没有一句话,我知道具体的格式,所以我宁愿使用ParseExact(我不明白为什么的CultureInfo将需要)。不过,我不断收到可怕的字符串未被识别为有效的DateTime异常。
There's no word in the date (like "September"), and I know the specific format, so I'd rather use ParseExact (and I don't see why CultureInfo would be needed). But I keep getting the dreaded "String was not recognized as a valid DateTime" exception.
感谢
一个小跟进。这里有3个办法,工作的:
A little follow up. Here are 3 approaches that work:
DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy", null);
DateTime.ParseExact("9/1/2009", "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime.Parse("9/1/2009", new CultureInfo("en-US"));
和这里有3不工作:
DateTime.ParseExact("9/1/2009", "M/d/yyyy", CultureInfo.CurrentCulture);
DateTime.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"));
DateTime.ParseExact("9/1/2009", "M/d/yyyy", null);
所以,解析()作品有EN-US,而不是ParseExact ......意外?
So, Parse() works with "en-US", but not ParseExact... Unexpected?
推荐答案
我怀疑问题出在格式字符串对那些数据的斜线。这是在格式字符串中的文化敏感日期分隔符,而最后一个参数是空
表示使用当前文化。如果你的或者的还有反斜杠(M'/'D'/'YYYY)的或的指定 CultureInfo.InvariantCulture
,一切都会好的。
I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null
means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture
, it will be okay.
如果任何人的兴趣再现这样的:
If anyone's interested in reproducing this:
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
这篇关于为什么不能DateTime.ParseExact()解析" 9/1/2009年"使用" M / D / YYYY"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!