C# 如何将 SQL 日期转换为 DateTime?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16634940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:31:08  来源:igfitidea点击:

How to convert a SQL date to a DateTime?

c#asp.netsql-server-2008datedatetime

提问by petros

I have a column with the datetype in my SQL database. How can I convert it to C# DateTimeand then back again to a SQL date?

date我的 SQL 数据库中有一个包含该类型的列。如何将其转换为 C# DateTime,然后再转换回 SQL date

回答by thunderbird

c# To get date from reader

c#从阅读器中获取日期

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

To insert date

插入日期

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 returns true on successful casting false otherwise.

否则,TryParse 在成功转换为 false 时返回 true。

VB

VB

To get date from reader

从读者处获取日期

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

To insert 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))

NOTE:Code is written in VB. You can easily write the c# equivalent of the above code. The function name remains the same in both VB and c#. Also CType is not available in c#(though its the same as explicitly casting a variable eg. date1=(DateTime)reader("dateColumn");I would recommend using TryParsewhich doesn't throw any exception on unsuccesful parses/casting.

注意:代码是用VB编写的。您可以轻松编写与上述代码等效的 c#。函数名在 VB 和 c# 中保持不变。此外,CType 在 c# 中不可用(尽管它与显式转换变量相同,例如。date1=(DateTime)reader("dateColumn");我建议使用TryParsewhich 不会在不成功的解析/转换时引发任何异常。

Syntax

句法

Date.TryParse(reader("dateColumn"), date1)

回答by Matthew

A sql DATEcan be directly cast to a .net DateTimeand vice-versa.

DATE可以将sql直接转换为 .net DateTime,反之亦然。

to get it, use the SqlDataReader.GetDatetime Method

要获取它,请使用SqlDataReader.GetDatetime 方法

DateTime myDate = myDataReader.GetDateTime(myColumnIndex);

to set it, simply assign it to the value of the SqlParameterand use the .Dateproperty of the DateTime

要设置它,只需将它分配给SqlParameter的值并使用.DateDateTime的属性

回答by Ravinther M

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

These code is working for me.Try these one

这些代码对我有用。试试这些