繁体   English   中英

从字符串转换日期和/或时间时转换失败

[英]Conversion failed when converting date and /or time from character string

将数据添加到数据库时,date_to和date_from中出现错误。 在sql server数据库中,date_to和date_from的数据类型是date。 建议一些解决方案

try
{
   cmd = new SqlCommand("insert into license1 values(@l_id,@customer_id,@d_id,@device_name,@from,@to)", cn);

   cmd.Parameters.AddWithValue("@l_id", license_id.Text);
   cmd.Parameters.AddWithValue("@customer_id", c_comboBox4.Text);
   cmd.Parameters.AddWithValue("@d_id", d_id_comboBox4.Text);
   cmd.Parameters.AddWithValue("@device_name", d_name_comboBox5.Text);
   cmd.Parameters.AddWithValue("@to", date_to.Text);
   cmd.Parameters.AddWithValue("@from", date_from.Text);

   cn.Open();
   a = cmd.ExecuteNonQuery();
   if (a > 0)
   {
      MessageBox.Show("Data Submitted");
   }

 }
 catch (Exception ex)
 {
      MessageBox.Show(ex.Message);
 }

转换到自己手中:

cmd.Parameters.AddWithValue("@to", DateTime.Parse( date_to.Text));
cmd.Parameters.AddWithValue("@from", DateTime.Parse( date_from.Text));

当仍然失败时,使用具有适当的Format和CultureInfo的DateTime.ParseExact()版本。

您可能需要考虑添加更强大和更广泛的验证层。 日期和数字对输入错误,用户设置和用户假设非常敏感。

总是假设TextBox.Text充满了错误。

如果用户输入日期格式为: yyyy-MM-dd尝试以下操作:

String strDateFormat= "yyyy-MM-dd";//change accordingly if format is something different
DateTime to=DateTime.ParseExact(date_to.Text,strDateFormat, CultureInfo.InvariantCulture);    
DateTime from=DateTime.ParseExact(date_from.Text, strDateFormat, CultureInfo.InvariantCulture);

cmd.Parameters.AddWithValue("@to", to);
cmd.Parameters.AddWithValue("@from", from);

尝试这个

 cmd.Parameters.AddWithValue("@to",Convert.ToDateTime(date_to.Text));
 cmd.Parameters.AddWithValue("@from",Convert.ToDateTime( date_from.Text});

我认为您的日期格式可能会导致问题。 您必须使用SQL提供程序支持的日期格式。 大多数SQL使用MM-dd-yyyy格式。 因此,如果你通过21-1-2014,SQL服务器不接受它,因为21个月不存在。

如果在执行代码时问题仍然存在,可能是由于两个重要原因:

  1. 您已使用DateTime.Now.ToShortString或类似的自动转换方法,和
  2. 您在设置中更改了计算机的默认日期时间格式。

更改计算机的日期时间格式或将自动转换更改为“解析”方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM