问题描述
我有一个看起来像这样的字符串:9/1/2009".我想将其转换为 DateTime 对象(使用 C#).
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);
日期中没有字词(例如September"),而且我知道具体的格式,所以我宁愿使用 ParseExact(我不明白为什么需要 CultureInfo).但我不断收到可怕的字符串未被识别为有效的日期时间"异常.
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 个不起作用:
And here are 3 that don't work:
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);
所以,Parse() 可用于en-US",但不能用于 ParseExact...出乎意料?
So, Parse() works with "en-US", but not ParseExact... Unexpected?
推荐答案
我怀疑问题在于格式字符串中的斜杠与数据中的斜杠.这是格式字符串中区分区域性的日期分隔符,最后一个参数 null
表示使用当前区域性".如果您要么转义斜线(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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!