处理不一致的日期格式字符串转换为DateTime

时间:2017-03-20 09:44:53

标签: c# string date type-conversion

想要从DateTime格式的以下字符串转换为datetime

"3/20/2017 4:03:03 PM"
"03/20/2017 4:03:03 PM"
"3/20/2017 04:03:03 PM"
"03/20/2017 04:03:03 PM"
etc

使用DateTime.ParseExact格式为"MM/dd/yyyy hh:mm:ss tt",但Format Exception已被捕获,是否有更好的方法可以执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以解析通过数组中所有自定义格式的日期:

string[] strDates = new string[]{"3/20/2017 4:03:03 PM"
                    ,"03/20/2017 4:03:03 PM"
                    ,"3/20/2017 04:03:03 PM"
                    ,"03/20/2017 04:03:03 PM"};

DateTime dt = DateTime.Now;
string[] strFormats = new string[] { "M/dd/yyyy h:mm:ss tt", "dd/MMM/yyyy h:mm:ss tt","MM/dd/yyyy h:mm:ss tt" };
foreach (var item in strDates)
{
    foreach (var format in strFormats)
    {
        dt = DateTime.ParseExact(item, format, CultureInfo.InvariantCulture);
    }
}

或直接传递数组:

dt = DateTime.ParseExact(item, strFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);

答案 1 :(得分:0)

试试这个,它会起作用

string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "3/20/2017 4:03:03 PM";
format = "M/dd/yyyy h:mm:ss tt";

  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }