无法从字符串中解析DateTime
string dt = "10/25/2010 11:40:05 PM"; var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU DateTime dateTime = DateTime.Parse(dt); //Exception!
如何解析那个dt
?
更新:在我的情况下,DateTime可以表示为"25.10.2010 11:40:05"
或"10/25/2010 11:40:05 PM"
这些是什么“通用”方法来解析它而不更改CurrentCulture?
使用自定义日期和时间格式字符串,使用ParseExact
或TryParseExact
。
DateTime dateTime; DateTime.TryParseExact( dt, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime );
由于俄罗斯文化不使用AM / PM,因此无法将字符串解析为俄语DateTime
表示,因此使用CultureInfo.InvariantCulture
这是一种美国文化(它代表没有特定的文化,但是模仿了en-US one)。
请尝试使用ParseExact
:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
尝试DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))
var result = DateTime.ParseExact(dt, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
为了避免运行时exception使用安全的DateTime.TryParseExact()方法,它会在解析不成功的情况下返回false,而不是抛出FormatExceptionexception
俄罗斯不使用AM和PM作为他们的AM / PM指示符,这至少是失败的一个原因。 另一个原因是俄罗斯可能不会使用“月/日/年”格式,据我所知,这种格式主要是美国的特点。 (我不记得俄罗斯的格式字符串;我确实记得,最近的月份名字让我感到悲痛,但这是另一个故事…)
我个人明确地将文化指定为不变文化,并明确指定格式字符串:
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);
如果合理地预期这会失败,则应该使用DateTime.TryParseExact
来优雅地处理失败而不涉及exception。
尝试这样的事情:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));