即使格式正确,DateTime.ParseExact也无法正常工作

时间:2018-12-26 11:39:20

标签: c# .net

DateTime.ParseExact给出了一个例外“字符串未被识别为有效的DateTime。”以下代码。

DateTime colValue = DateTime.ParseExact("11-Oct-18 11:15:13 AM", "dd-MM-yyyy hh:mm:ss",
                                   CultureInfo.InvariantCulture);

为什么这不起作用?

2 个答案:

答案 0 :(得分:3)

面具中有几处需要修复:

  • 长月=> MMM
  • 您正在使用短年=> yy
  • 您需要指出AM / PM => tt
  • 时分秒应支持一位数字=> h:m:s
DateTime colValue = DateTime.ParseExact(
    "11-Oct-18 11:15:13 AM", 
    "dd-MMM-yy h:m:s tt", 
    CultureInfo.InvariantCulture);

答案 1 :(得分:0)

之所以可行,是因为我们将hh替换为h,将mm替换为m,将ss替换为s,并且还添加了tt来捕获AM或PM:

        DateTime colValue = DateTime.ParseExact("11-Oct-18 11:15:13 AM", "dd-MMM-yy h:m:s tt",
                               System.Globalization.CultureInfo.InvariantCulture);

感谢@Jerin Sebastian

相关问题