简体   繁体   中英

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

It doesn't work because the month is indicated with one digit but in the format string there are two MM. If you want to use ParseExact "the format of the string representation must match the specified format exactly." https://msdn.microsoft.com/en-us/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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