Domanda

Why does the following code generate a 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?

È stato utile?

Soluzione

You need to include CultureInfo, for example:

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. You can also use CultureInfo.InvariantCulture and it will work. Jon Skeet provides some detailed explanation here.

Altri suggerimenti

depends on your culture, to take that out of the equation....

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

According to the documentation, a FormatException is thrown, given one of these conditions:

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider
) 
  • s or format is an empty string.
  • s does not contain a date and time that corresponds to the pattern specified in format.
  • The hour component and the AM/PM designator in s do not agree.

If you pass in a null IFormatProvider, I think it defaults to the current thread's culture. I'd have to look at this in Reflector. Is there any reason you wanted to pass in null?

UPDATE:

I looked at it in .NET Reflector and it defaults to the current thread's DateTimeFormatInfo. I don't know if I'm allowed to post the code here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top