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

datetime format in ASP.NET C# not recognized

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

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();
}

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

String was not recognized as a valid DateTime

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

我曾尝试直接显示 dt.Rows[0][0] 内容,但随后收到有关日期不在公历中的错误。

我可以采取任何步骤来了解这是怎么回事吗?

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

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

您应该使用 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://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 语句