我有一个看起来像这样的字符串:“9/1/2009”。我想将其转换为 DateTime 对象(使用 C#)。
这有效:
DateTime.Parse("9/1/2009", new CultureInfo("en-US"));
但我不明白为什么这不起作用:
DateTime.ParseExact("9/1/2009", "M/d/yyyy", null);
日期中没有单词(比如“September”),而且我知道具体的格式,所以我宁愿使用 ParseExact(我不明白为什么需要 CultureInfo)。但我不断收到可怕的“字符串未被识别为有效的日期时间”异常。
谢谢
一点跟进。以下是 3 种可行的方法:
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);
因此,Parse() 与“en-US”一起使用,但 ParseExact 不适用……出乎意料?