简体   繁体   English

DateTime.Parse抛出字符串无法识别,我看不到为什么

[英]DateTime.Parse throwing string not recognized, I cannot see why

I cannot understand why this is throwing "String was not recognized as a valid DateTime" 我不明白为什么这会引发“字符串未被识别为有效的DateTime”

        string[] formats = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
               "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
               "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
               "M/d/yyyy h:mm", "M/d/yyyy h:mm", "MM/dd/yyyy hh:mm",
               "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
               "MM/d/yyyy HH:mm:ss.ffffff" };
    var delimit = line.Split(',');
    try
    {
        id = delimit[0];
        DateTime.TryParseExact(delimit[1].Trim(),formats,new CultureInfo("en-US"),DateTimeStyles.None, out openDate);
        delimit[5] = delimit[5].Replace("\"","");
        closedDate = DateTime.ParseExact(delimit[5].Trim(),formats,new CultureInfo("en-US"),DateTimeStyles.None);
        DateTime.TryParseExact(delimit[5].Trim(),formats,new CultureInfo("en-US"),DateTimeStyles.None, out closedDate);
        severity = delimit[7].Split('-').Last().Trim();
        state = delimit[6].Trim();
    }
    catch(Exception e)
    {

        Console.WriteLine(line);
    }

The entry it throws on is : 它引发的条目是: 在此处输入图片说明

The formats array should include the 24 hour time format. 格式数组应包含24小时制。

Either dd/MM/yyyy HH:mm OR MM/dd/yyyy HH:mm OR M/d/yyyy HH:mm OR d/M/yyyy H:m format can be used. 可以使用dd/MM/yyyy HH:mmMM/dd/yyyy HH:mmM/d/yyyy HH:mmd/M/yyyy H:m格式。

Please note that only you know whether your format is dd-MM-yyyy or MM-dd-yyyy as for both date and month places you have 12. 请注意,只有12的日期和月份,您才知道格式是dd-MM-yyyy还是MM-dd-yyyy。

You can check the sample inputs to your code and depending on those you should choose the format carefully. 您可以检查代码的示例输入,并根据这些输入仔细选择格式。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM