如何转换为SQL日期为DateTime? [英] How to convert a SQL date to a DateTime?

查看:139
本文介绍了如何转换为SQL日期为DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有的键入日期在我的SQL数据库中的列。我怎样才能将其转换为C#的DateTime ,然后再返回到一个SQL 日期

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

推荐答案

C#
为了从读者日期

c# To get date from reader

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成功铸造否则为false返回true。

TryParse returns true on successful casting false otherwise.

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

请注意:code是用VB写。您可以轻松地编写C#相当于上述code的。函数名称仍保留在VB和C#一样的。另外CTYPE是不是在C#中使用(虽然它一样明确铸造变量如日期1 =(DateTime的)读卡器(dateColumn); 我会建议使用的TryParse 不扔在不成功的解析/铸造任何异常。

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 TryParse which doesn't throw any exception on unsuccesful parses/casting.

语法

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

这篇关于如何转换为SQL日期为DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆