字符串到日期时间无法转换 - C#

Mer*_*rve 1 c# string datetime

我在MSDN中找到了一个用于字符串到日期时间转换的示例.但它不起作用,落入catch().为什么这个代码块不起作用?

DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

你正在使用当前文化中关于日期/时间格式的想法 - 而我的猜测是你处于一个通常在一个月之前出现的文化.

如果您知道格式,我通常会使用不变的文化TryParseExact- 并且- 绝对使用Parse和catch块; 使用TryParseExactTryParse.在这种情况下:

if (DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
                           CultureInfo.InvariantCulture, 0, out dateValue))
{
    Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
else
{
    Console.WriteLine("Unable to convert '{0}'.", dateString);
}
Run Code Online (Sandbox Code Playgroud)

如果你知道输入格式,但是你知道要使用的文化,我只会使用DateTime.TryParse适当的文化.