繁体   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);
        }
    }
}

我想将varchar变量解析为保存在SQL Server中的datetime

它不起作用,因为月份用一位数字表示,但是格式字符串中有两个MM。 如果要使用ParseExact,“字符串表示形式的格式必须与指定的格式完全匹配。” https://msdn.microsoft.com/zh-CN/library/w2sa9yss%28v=vs.110%29.aspx

如果您无法更改将日期保存在数据库中的方式,则需要找到其他策略。

暂无
暂无

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

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