在c#中将字符串转换为日期时间格式时出错

时间:2013-10-24 12:11:29

标签: c# c#-4.0 c#-3.0

我在执行sqlcommand时收到错误“将varchar数据类型转换为日期时间数据类型导致超出范围的值。”。日期时间的输入为“ 10/24/2013 06:25:30 PM ” // C#代码

    string sa1 = dateTimePicker1.Value.ToString("MM/dd/yyyy");
    string fr = textBox1.Text;
    string dt = sa1 + " " + fr;
    string to = textBox2.Text;
    string dt1 = sa1 + " " + to;

    DateTime tim = DateTime.ParseExact(dt.ToString(), "MM/dd/yyyy hh:mm:ss tt",System.Globalization.CultureInfo.InvariantCulture);
    DateTime tim1 = DateTime.ParseExact(dt1.ToString(), "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
    DateTime tim2 = Convert.ToDateTime(tim);
    DateTime tim3 = Convert.ToDateTime(tim1);
    dataGridView1.Rows.Clear();
    SqlConnection con = new SqlConnection("Data Source=173.83.250.71,1433; Network Library=DBMSSOCN; Initial Catalog=paradigm;User Id=sa; password=Paradigm123");
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into paradigm.dbo.driverotcalc ( emp_no, fro, too, purpose, totalhrs, entdate, amount) values('" + emp.ToString() + "','" + tim2.ToString() + "','" + tim3.ToString() + "','" + textBox3.Text + "','" + textBox4.Text + "','" + DateTime.Now + "','" + textBox5.Text + "')",con);

    cmd.ExecuteNonQuery();

任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您插入DateTime.Now。我怀疑格式与数据库中的日期格式不同。 试试:

string formatDB ="YYYY/MM/dd";
DateTime.Now.ToString(formatDB);

将formatDB替换为数据库中的日期格式