ASP.NET C#中的日期时间格式无法识别

时间:2018-04-11 03:01:43

标签: c# asp.net datetime ado.net string-parsing

我的数据库中有一列包含以下内容:

status
2018-12-31 15:31:56.000 (result of a select in SMSS)

我试图通过C#中的查询在ASP.NET代码页面中获取此列的数据:

var connectionString = System.Configuration.ConfigurationManager.AppSettings["connection"];
SqlConnection con = new SqlConnection(connectionString);

DataTable dt = new DataTable();            

SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 [status] from [tablename] where idNo = '" + idNo+ "'", con);

con.Open();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    Debug.WriteLine("\n Rows extracted."); // -> Error thrown here.

    Debug.WriteLine("\n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss.000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));

    con.Close();
    da.Dispose();
}

无论我尝试什么,我总是得到

  

字符串未被识别为有效的DateTime

或日期时间未被识别为公历的一部分。

我试图直接显示dt.Rows[0][0]内容,但后来我得到的错误是关于不在公历中的日期。

我是否可以采取任何措施来了解这是怎么回事?

使用DateTime是C#的绝对噩梦,我希望MS能最终解决这个问题。

请不要指向文档或其他文章,这显然是我的来源......

2 个答案:

答案 0 :(得分:3)

格式化字符串时,大小写非常重要。请参阅:https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

您真正想要的字符串是:

yyyy-MM-dd HH:mm:ss.fff

请注意月,小时和分钟的情况。

h = 12小时制,H = 24小时制。

Demo

现在您只需要采用最佳实践来调用数据库。使用参数化查询并阅读using语句

答案 1 :(得分:2)

您应该使用MM(大写)表示月份,mm(小写)表示分钟。

 if (dt.Rows.Count > 0)
        {
          Debug.WriteLine("\n Rows extracted."); // -> Error thrown here.

          Debug.WriteLine("\n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));

          con.Close();
          da.Dispose();
        }

注意:请不要在查询中连接数据,这将是黑客对SQL注入的邀请。改为使用参数化查询

更多信息:https://stackoverflow.com/a/7505842/2131576