[英]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();
}
無論我嘗試什么,我總會得到
字符串未被識別為有效的DateTime
或日期時間不被認為是公歷的一部分。
我試圖直接顯示dt.Rows[0][0]
內容,但是我收到一個關於日期不在格里高利歷中的錯誤。
我可以采取任何步驟來了解此情況嗎?
在C#中,使用DateTime
是絕對的噩夢,我希望MS能夠最終解決此問題。
請不要將我指向文檔或其他文章,這顯然是我來自...
格式化字符串時,大小寫很重要。 請參閱: https : //docs.microsoft.com/zh-cn/dotnet/standard/base-types/custom-date-and-time-format-strings
您實際想要的字符串是:
yyyy-MM-dd HH:mm:ss.fff
請注意月份,小時和分鍾的大小寫。
h = 12小時制,H = 24小時制。
現在,您只需要采用最佳實踐來調用數據庫。 使用參數化查詢並閱讀using語句
您應該使用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注入。 改用參數化查詢
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.