Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact FormatException

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?

like image 775
Maxim V. Pavlov Avatar asked Sep 16 '26 04:09

Maxim V. Pavlov


2 Answers

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.

like image 108
doblak Avatar answered Sep 17 '26 23:09

doblak


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

DateTime.ParseExact("03/01/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
like image 27
Keith Nicholas Avatar answered Sep 17 '26 23:09

Keith Nicholas