从字符串转换为datetime时,字符串未被识别为有效的DateTime

时间:2012-10-18 06:45:57

标签: string datetime

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

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

代码:

capture = Convert.ToDateTime(newRecord.CaptureTime),

2 个答案:

答案 0 :(得分: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()。阅读更多here

答案 1 :(得分:1)

问题是用最后一个冒号(':')代替。 09/25/2012 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);