سؤال

The user enters the date as MM/DD/YYYY in a string and it needs to be formatted in C#/ASP.NET for insertion into a SQL Server 2008 R2 record. I understand I should convert it to a datetime and parameterize it into the query, but can't find an example of this.

What is the easiest way to do this?

هل كانت مفيدة؟

المحلول

Use DateTime.Parse and in your query add the re turned DateTime as parameter.

var date = DateTime.Parse(theString);
SqlCommand cmd = new SqlCommand("insert into xxx (theDateField) values(@param1)", con);
cmd.Parameters.AddWithValue("param1", date);

//execute your query and do what even you want.

نصائح أخرى

I understand that question is answered but this might be also helpful

DateTime regDate = DateTime.MinValue;

    if (txtDate.Text.Trim().Length > 0)
    {
        string[] ddmmyyyy = txtDate.Text.Trim().Split(new char[] { '-', '/' });
        regDate = Convert.ToDateTime(ddmmyyyy[1] + "/" + ddmmyyyy[0] + "/" + ddmmyyyy[2]);
    }

Now your date is ready you can insert in database using whatever method you like.

cmd.Parameters.AddWithValue("@RegDate", regDate);

or

SqlParameter paramRegDate = new SqlParameter("@RegDate", SqlDbType.DateTime);
selCmd.Parameters.Add(paramRegDate);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top