我该如何解析这个日期时间字符串?

Jas*_*n94 5 c# string datetime datetime-parsing

我无法弄清楚,我哪里出错了?

我得到了以下日期时间字符串,需要将其解析为datetime:

string timestr = "1/20/2014 12:05:16 AM"
Run Code Online (Sandbox Code Playgroud)

我试图像这样解析它:

DateTime.ParseExact( timestr,
                     "MM/dd/yyyy hh:mm:ss tt",
                     null);
Run Code Online (Sandbox Code Playgroud)

当试图这样做时它返回

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

有提示吗?

Son*_*nül 12

MM0112

使用M而不是这是112.

string timestr = "1/20/2014 12:05:16 AM";
var date = DateTime.ParseExact(timestr,
                               "M/dd/yyyy hh:mm:ss tt",
                               CultureInfo.InvariantCulture);
Console.WriteLine(date);
Run Code Online (Sandbox Code Playgroud)

输出将是;

1/20/2014 12:05:16 AM
Run Code Online (Sandbox Code Playgroud)

这里一个demonstration.

有关更多信息,请查看;

还要注意你的小时格式.hh0112,HH0023.如果你的小时13,1415等等.hh格式将失败.

而且,由于您使用的是null作为一个IFormatProvider在你的DateTime.ParseExact方法,这意味着它使用CurrentCulture默认.如果DateSeparator不是这样/,你的方法FormatException 甚至会抛出你的字符串和格式匹配,因为"/"格式说明符在自定义日期和时间格式中具有特殊含义,如:替换我当前的文化或提供的文化日期分隔符