Kannan
Kannan

Reputation: 829

correct procedure to convert string date (using jquery datepicker ) to date time in c#

I have faced issues while inserting date from c# to SQL Server. What is the correct method to insert date from c# to a column which is in DateTime to SQL Server.

Currently my method is to convert the string date to DateTime format and then insert into database.

Datetime dt = Convert.ToDateTime(txtDate.Text.Trim());

Doing so I have come across an error where the current system date conflicts with the newly converted date. What is the correct way to insert string date into database ?

Upvotes: 0

Views: 2031

Answers (2)

Habib
Habib

Reputation: 223332

Use SqlParameter and form a parameterized query. In that manner you will pass the .Net DateTime object to SQL Server.

Something like:

using (SqlConnection con = new SqlConnection("yourconnectionstring"))
using (SqlCommand cmd = new SqlCommand("INSERT into yourTable([DateCol]) VALUES (@pDate)", con))
{
    cmd.Parameters.AddWithValue("@pDate", DateTime.Now);
    con.Open();
    cmd.ExecuteNonQuery();
}

For your question:

What is the correct way to insert string date into database ?

Don't. Instead convert the date string to DateTime object and then insert it into the database using parameterized query.

For your comment:

how will you convert string date(using jquery datepicker) to datetime format?

You can use DateTime.ParseExact for the format for your datetime picker and convert the string into DateTime object.

For example if your DateTime picker format is: mm/dd/yyyy then you can try:

DateTime dt = DateTime.ParseExact(dateString, "mm/dd/yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Stefano Altieri
Stefano Altieri

Reputation: 4628

Create a query with parameters like this

SqlCommand cmd = new SqlCommand ("insert into T (...) values (@d",db);
cmd.Parameters.AddWithValue("@d",Convert.ToDateTime(txtDate.Text.Trim());
//...

Upvotes: 0

Related Questions