简体   繁体   English

DateTime.ParseExact FormatException

[英]DateTime.ParseExact FormatException

Why does the following code generate a FormatException? 为什么以下代码生成FormatException?

DateTime.ParseExact("03/01/2012", "dd/MM/yyyy", null);

DateTime.ParseExact

Perhaps it has something to do with the fact that the code is running under IIS 7.5 Express as a part of an MVC3 site execution logic? 也许这与代码在IIS 7.5 Express下作为MVC3站点执行逻辑的一部分运行这一事实有关?

You need to include CultureInfo, for example: 您需要包含CultureInfo,例如:

DateTime.ParseExact("03/01/2012", "dd/MM/yyyy", new CultureInfo("en-US"));

Slashes in format string are culture sensitive and if you don't pass in CultureInfo, current culture is used. 格式字符串中的斜杠对文化敏感,如果未传入CultureInfo,则使用当前文化。 You can also use CultureInfo.InvariantCulture and it will work. 您也可以使用CultureInfo.InvariantCulture ,它将起作用。 Jon Skeet provides some detailed explanation here. Jon Skeet在这里提供了一些详细的解释。

取决于你的文化,取决于你的等式....

DateTime.ParseExact("03/01/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);

According to the documentation , a FormatException is thrown, given one of these conditions: 根据文档 ,在给定以下条件之一的情况下抛出FormatException

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider
) 
  • s or format is an empty string. s或format是一个空字符串。
  • s does not contain a date and time that corresponds to the pattern specified in format. s不包含与格式中指定的模式对应的日期和时间。
  • The hour component and the AM/PM designator in s do not agree. s中的小时组件和AM / PM指示符不一致。

If you pass in a null IFormatProvider , I think it defaults to the current thread's culture. 如果你传入一个空的IFormatProvider ,我认为它默认为当前线程的文化。 I'd have to look at this in Reflector. 我必须在Reflector中看一下这个。 Is there any reason you wanted to pass in null ? 你有什么理由想传入null吗?

UPDATE: 更新:

I looked at it in .NET Reflector and it defaults to the current thread's DateTimeFormatInfo . 我在.NET Reflector中查看它,它默认为当前线程的DateTimeFormatInfo I don't know if I'm allowed to post the code here. 我不知道是否允许我在这里发布代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM