.NET DateTime.ParseNET、DateTime、Parse

2023-09-04 00:15:05 作者:秋离未离

当试图用解析方法上的DateTime类我得到一个异常抛出:

When trying to use the Parse method on the DateTime class I get an exception thrown:

字符串未被识别为有效的DateTime。

String was not recognized as a valid DateTime. 在输出时串读作26/10/2009上午08点47分39秒。 在此字符串是由一组获得从一个正则表达式匹配。 在没有从这场比赛后得到的将解析为datetime的字符串。 (WTF?)

其他字符串的例子:


26/10/2009 8:47:39 AM
26/10/2009 8:00:41 AM
26/10/2009 7:48:35 AM

奇怪的是,我相信它之前&GT的工作; __<

推荐答案

解析 需要区域设置(当前线程的文化)考虑在内。因此,我会使用 ParseExact 和一个不变的文化显式地指定了正确的格式(或你所需要的文化,如:的en-US ,用于AM / PM)。

Parse takes regional settings (culture of current thread) into account. Therefore, I'd use ParseExact and specify the correct format explicitly with an invariant culture (or the culture you need, eg. en-US, for AM/PM).