简体   繁体   English

将字符串从SQL Server数据库解析为DateTime变量…异常“字符串未被识别为有效的DateTime。”

[英]Parsing string from SQL Server database into DateTime variable… exception “String was not recognized as a valid DateTime.”

string str,a;
DateTime dat, aa;

using (con = new SqlConnection(@"Data Source=daniyal\sqlexpress;Initial Catalog=webassign;Integrated Security=True"))
{
    con.Open();

    using(com = new SqlCommand("select * from tasks",con))
    {
        rdr = com.ExecuteReader();

        while (rdr.Read())
        {
            str = rdr.GetValue(1).ToString();
            dat = DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        }
    }
}

I want to parse a varchar variable into datetime saved in my SQL Server 我想将varchar变量解析为保存在SQL Server中的datetime

It doesn't work because the month is indicated with one digit but in the format string there are two MM. 它不起作用,因为月份用一位数字表示,但是格式字符串中有两个MM。 If you want to use ParseExact "the format of the string representation must match the specified format exactly." 如果要使用ParseExact,“字符串表示形式的格式必须与指定的格式完全匹配。” https://msdn.microsoft.com/en-us/library/w2sa9yss%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-CN/library/w2sa9yss%28v=vs.110%29.aspx

If you can't change the way you save the date in the database you need to find another strategy. 如果您无法更改将日期保存在数据库中的方式,则需要找到其他策略。

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

相关问题 无法将字符串识别为有效的DateTime。 引发异常 - String was not recognized as a valid DateTime. Throws an Exception 迄今为止的字符串解析错误“字符串未被识别为有效的DateTime。” - String to date parsing error “String was not recognized as a valid DateTime.” 字符串日期未被识别为有效的日期时间。 - String date was not recognized as a valid DateTime.' 无法将字符串识别为有效的DateTime。 在Windows Server 2012上使用ParseExact - String was not recognized as a valid DateTime. using ParseExact on Windows Server 2012 错误消息为“字符串未被识别为有效的DateTime。” - Error Message as “String was not recognized as a valid DateTime.” 无法将字符串识别为有效的DateTime。 :仅服务器错误 - String was not recognized as a valid DateTime. : Error only in Server 错误:字符串未被识别为有效的DateTime。 - Error: String was not recognized as a valid DateTime. 获取错误“字符串未被识别为有效的DateTime”。 - Getting error “String was not recognized as a valid DateTime.” 字符串未被识别为有效的日期时间。 将字符串转换为日期时间 - String was not recognized as a valid DateTime. Converting string to DateTime DateTime.ParseExact赋予String未被识别为有效的DateTime。 - DateTime.ParseExact gives String was not recognized as a valid DateTime.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM