Click here to Skip to main content
15,903,841 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i am using ajax calender,so that i am taking date from a textbox.

when i am taking it from textbox,it is a string and like 26/01/2011

and i want to put it in database,my database datatype id DateTime,so that i want to convert it to DateTime

So i used Convert.ToDatetime(txtDate.Text)

Then i got 26/1/2011 12:00:00 AM

This is not supported by sql server DateTime Datat Type

Please help me to do it.

The way i did:

C#
string joindate = txtJdate.Text;
               string dobdate = txtDob.Text;
               DateTime join, dob;
               join = Convert.ToDateTime(joindate);
               dob = Convert.ToDateTime(dobdate);
obj.IDUCommand("insert into tbl_empdetails values(" + dob + "," + join + ")")


The corresponding sql query is :

insert into tbl_empdetails values(18/1/2011 12:00:00 AM,25/1/2011 12:00:00 AM)

The error is :

" Incorrect syntax near 12 "
Posted
Updated 26-Jan-11 18:19pm
v4

It's because of the way you put it into the database. You have (deliberately or accidentally) converted it from a DateTime to a string: probably by saying something like:
SqlCommand com = new SqlCommand("INSERT INTO myTable (date) VALUES ('" + myDateTime + "')", con);
Unfortunatley, SQL expects data strings in ISO format: "yyyy/MM/dd hh:mm:ss" which your locale does not do by default.

The best solution is to use parametrized queries instead:
SqlCommand com = new SqlCommand("INSERT INTO myTable (date) VALUES (@DT)", con);
com.Parameters.AddWithValue("@DT", myDateTime);
This has the additional advantage of not being prone to SQL Injection attacks, and is worth doing for all database access.
 
Share this answer
 
Comments
JF2015 26-Jan-11 6:58am    
Good answer. +5
DateTime DOJ = DateTime.ParseExact(txtJdate.Text,"dd/MM/yyyy",null);
then pass in table and its working at my side.
 
Share this answer
 
using the following statement is better...
C#
DateTime DOJ;
if (DateTime.TryParseExact(txtJdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DOJ))
{
//Do what ever u want with that date...   
}
else
{
// invalid date format...
}
 
Share this answer
 
v2
Use like this:
Convert.ToDateTime(txtJdate.Text).ToString("yyyy-mm-dd");

Thank You all


Kishore R
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900