【问题标题】:Parsing string from SQL Server database into DateTime variable..... exception "String was not recognized as a valid DateTime."将 SQL Server 数据库中的字符串解析为 DateTime 变量.....异常“字符串未被识别为有效的 DateTime”。
【发布时间】:2015-05-02 15:44:55
【问题描述】:
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 中的日期时间

【问题讨论】:

  • 你解析的是s而不是str,是不是打错字了?无论如何,您解析的字符串的确切值是多少?
  • 请发布您的数据如何存储在 Sql Server 中的示例,例如2014 年 12 月 5 日?
  • 可能是日期格式不匹配,或者SQL中的值为空。
  • dd/MM/yyy 应该是 dd/MM/yyyy

标签: c# asp.net sql-server-2012 datetime-format


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多