Link to home
Start Free TrialLog in
Avatar of nextmedstaff
nextmedstaffFlag for United States of America

asked on

Converting string to Date for sql C#

I have a C# application that loops through an excel file and grabs the values from the fields to insert into our sql database. One of the fields in the excel file has dates in the following format 4/13/2012. This value is supposed to go into a datetime field in sql server, yet no matter what i try I keep getting an error inserting it. What is the best way to go about taking a string such as 4/12/2012 and getting it into the database. Also will i need single quotes around the value in the query or not? Thanks for any help.
Avatar of Ashok
Ashok
Flag of United States of America image

use parameter

DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (
    ...
                                                          ,[FirstDate]
    ...
    ) VALUES (@FirstDate,...");

   db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );

HTH
Ashok
cmdInsert = New SqlCommand("INSERT INTO [empbill] ([deptcode], [personNo], [entrydate]) VALUES (@deptcode, @personNo, @entrydate);", db)
cmdInsert.Parameters.AddWithValue("deptcode", eno.Text)
cmdInsert.Parameters.AddWithValue("personNo", TextBox5.Text)
cmdInsert.Parameters.AddWithValue("entrydate", dd.Text)

HTH
Avatar of nextmedstaff

ASKER

So I figured out what the problem is, the excel file we receive has the cells formatted as a date.. for whatever reason when my application reads in the value it wants to read in a double value. I went to the excel file and converted the cells to General and im now seeing where my program is pulling that double value from. 41085 is the format they are in. Is there a way to convert that to a date in C#??
ASKER CERTIFIED SOLUTION
Avatar of nextmedstaff
nextmedstaff
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
After hours of troulbe shooting and researching google I found the solution and it worked.