簡體   English   中英

如何將SQL日期轉換為DateTime?

[英]How to convert a SQL date to a DateTime?

我的SQL數據庫中有一個包含date類型的列。 如何將其轉換為C# DateTime ,然后再將其轉換回SQL date

sql DATE可以直接轉換為.net DateTime ,反之亦然。

為了得到它,使用SqlDataReader.GetDatetime方法

DateTime myDate = myDataReader.GetDateTime(myColumnIndex);

設置它,只需將其分配給SqlParameter的值並使用DateTime的.Date屬性

c#從讀者那里獲取日期

DateTime date1;
DateTime.TryParse(reader["datecolumn"], out date1);

要插入日期

string date1="2013-12-12"; 
DateTime date2;
DateTime.TryParse(reader["datecolumn"],out date2);

SqlCommand cmd= new SqlCommand("Insert into table (dateColumn) Values(@date2)",connection);
cmd.Parameters.AddWithValue("@date2",date2.Date);

TryParse在成功轉換時返回true,否則返回false。

VB

從讀者那里得到日期

Dim date1 as Date=CType(reader("dateColumn"),Date)

要插入日期

 Dim date1 as String="2013-12-12" 'you can get this date from an html input of type date

 Dim cmd As New SqlCommand("Insert into table (dateColumn) Values(@date1)",connection)
 cmd.Parameters.AddWithValue("@date1",CType(date1, Date))

注意:代碼是用VB編寫的。 您可以輕松編寫上述代碼的c#等價物。 函數名在VB和c#中保持不變。 此外,cype在c#中不可用(盡管它與顯式轉換變量相同,例如date1=(DateTime)reader("dateColumn");我建議使用TryParse ,它不會對不成功的解析/轉換拋出任何異常。

句法

Date.TryParse(reader("dateColumn"), date1)
 string mydate= Convert.ToDateTime(reader["dateColumn"]).ToShortDateString().ToString());

這些代碼對我有用。試試這些

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM