How to convert SQL date to DateTime?

I have a column of type date in my SQL database. How to convert it to C # DateTime and then return to SQL date ?

+8
date c # datetime sql-server-2008
source share
3 answers

A sql DATE can be directly passed to .net DateTime and vice versa.

to get it, use the SqlDataReader.GetDatetime Method

 DateTime myDate = myDataReader.GetDateTime(myColumnIndex); 

to set it, simply set it to SqlParameter and use the .Date property for DateTime

+9
source share

C # To get a date from a reader

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

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 if casting false otherwise.

B. B.

To get a date from the reader

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

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: The code is written in VB. You can easily write the C # equivalent of the specified code. The function name remains unchanged for both VB and C #. CType is also not available in C # (although it is the same as explicit casting of a variable, for example. date1=(DateTime)reader("dateColumn"); I would recommend using TryParse , which does not throw any exceptions for unsuccessful analysis / casting.

Syntax

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

This code works for me. Try these

+1
source share

All Articles