You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ASP.NET在SQL Server 2012存储日期时间时遭遇字符串转换错误

解决ASP.NET向SQL Server 2012存储日期时间时的转换错误

嘿,这个“Conversion failed when converting date and/or time from character string”错误我之前踩过好几次!咱们一步步理清问题根源,再给出靠谱的解决办法:

错误到底出在哪?

你的代码里把输入日期转成了dd/MM/yyyy格式的字符串,时间转成了长格式字符串,但如果直接把这些格式化后的字符串拼接进SQL语句里,会触发两个问题:

  • SQL Server默认的日期解析格式和你输出的dd/MM/yyyy可能不兼容(比如系统区域是月/日/年的话,31/12/2024会被判定为无效日期)
  • 直接拼接字符串不仅容易出转换错误,还存在SQL注入的安全隐患

最优解决方案:用参数化查询(强烈推荐)

这是既解决转换问题又保障安全的最佳方式,直接把DateTime类型的值传给SQL参数,让ADO.NET和SQL Server自动处理类型转换,完全不用手动格式化字符串。

修改你的代码如下:

protected void btnSubmit_Click(object sender, EventArgs e) 
{
    // 合并日期和时间为完整的DateTime对象
    DateTime inputDate = Convert.ToDateTime(txtdate.Text);
    DateTime inputTime = Convert.ToDateTime(txttime.Text);
    DateTime fullDateTime = new DateTime(inputDate.Year, inputDate.Month, inputDate.Day, 
                                        inputTime.Hour, inputTime.Minute, inputTime.Second);

    // 保留你原来的显示逻辑
    lbldate.Text = fullDateTime.ToString("dd/MM/yyyy");
    lbltime.Text = fullDateTime.ToLongTimeString();

    // 用参数化查询插入数据库
    string connectionString = @"Data Source=DESKTOP-O6SE533;Initial ..."; // 补全你的完整连接字符串
    string sqlQuery = "INSERT INTO YourTableName (YourDateTimeColumn) VALUES (@FullDateTime)";

    // 使用using自动释放资源,避免连接泄漏
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
        {
            // 添加参数,直接传递DateTime类型
            cmd.Parameters.AddWithValue("@FullDateTime", fullDateTime);
            
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

备选方案:如果必须用字符串传递(不推荐)

要是因为特殊情况非得传字符串,那得确保SQL Server能正确解析它:

  • 把日期时间转成SQL Server认可的标准格式,比如yyyy-MM-dd HH:mm:ss:
    string sqlSafeDateTime = fullDateTime.ToString("yyyy-MM-dd HH:mm:ss");
    
  • 或者在SQL语句里用CONVERT函数指定格式代码(103对应dd/MM/yyyy):
    INSERT INTO YourTableName (YourDateTimeColumn) VALUES (CONVERT(datetime, @DateStr, 103))
    

但还是那句话,参数化查询才是最稳妥的选择。

额外小提示

可以用DateTime.TryParseExact来更安全地解析用户输入,避免无效格式的输入导致报错:

DateTime parsedDate;
if (!DateTime.TryParseExact(txtdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
{
    lbldate.Text = "日期格式错误,请输入dd/MM/yyyy格式";
    return;
}

内容的提问来源于stack exchange,提问作者Vishal Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:33:39