0

尝试将字符串转换为日期时间时出现此错误“字符串未被识别为有效的日期时间”

我的字符串值:“09/25/2012 11:00:36:156”

代码 :

capture = Convert.ToDateTime(newRecord.CaptureTime),
4

2 回答 2

2

我建议您使用正则表达式。您将拥有验证输入字符串和强大的 DateTime 转换机制:

void Main()
{
    string datestring = "09/25/2012 11:00:36:156";

    string regexpr = @"(?x)(?i)
                    (\d{1,4}) [./-]
                    (\d{1,2}) [./-]
                    (\d{1,4}) [\sT]  (\d+):(\d+):(\d+) \s? (A\.?M\.?|P\.?M\.?)?";

    DateTime capture = new DateTime(); // set to default value in case datestring isn't valid

    if (Regex.IsMatch(datestring, regexpr)
        && DateTime.TryParse(Regex.Match(datestring, regexpr).Groups[0].Value, out capture))
    {    
        // convert is succeded
    }
    else
    {
        // Handle invalid dateString
    }

    Console.WriteLine(capture);
}

DateTime.TryParseExact()在这里阅读更多。

于 2012-10-18T07:10:22.587 回答
1

问题在于最后一个冒号 (':') 替换为 . 2012 年 9 月 25 日 11:00:36:156

        var dateString = "09/25/2012 11:00:36:156";
        var modifiedString = dateString.Substring(0, dateString.Length - 4) + "." + dateString.Substring(20);
        //var modifiedString = dateString.Substring(0, dateString.Length - 4);
        var dateValue = Convert.ToDateTime(modifiedString);
于 2012-10-18T06:56:34.087 回答