问题
string dt = "10/25/2010 11:40:05 PM";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
How to parse that dt
?
UPDATE:
In my case DateTime can be represent as "25.10.2010 11:40:05"
or "10/25/2010 11:40:05 PM"
Is these any "generic" method to parse it without changing CurrentCulture?
回答1:
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).
回答2:
Try using ParseExact
instead:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
回答3:
Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))
回答4:
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
回答5:
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.
回答6:
Try something like this:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));
来源:https://stackoverflow.com/questions/7854529/unable-to-parse-datetime-from-a-string