string dt = \"10/25/2010 11:40:05 PM\";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
Use a custom Date and Time format string, using either ParseExact
or TryParseExact.
DateTime dateTime;
DateTime.TryParseExact(
dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime
);
The string cannot be parsed as a Russian DateTime
representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture
which is a US like culture (it represents no specific culture, but is modeled after the en-US one).
Try something like this:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));
Try using ParseExact
instead:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)
I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:
string text = "10/25/2010 11:40:05 PM";
string pattern = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(text, pattern,
CultureInfo.InvariantCulture);
If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.
var result = DateTime.ParseExact(dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception
Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))