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

C#中DateTime与字符串时间比较报类型不匹配错误

报错原因

C#为强类型语言,代码中data是DateTime类型,直接与字符串"09:00"通过>运算符比较时,两种类型未定义对应比较逻辑,因此抛出类型不匹配错误。
现有实现另外存在两处明显问题:

  • 仅判断时间晚于9点,未设置营业结束时间校验,逻辑不完整
  • SQL语句直接拼接用户输入内容,存在严重SQL注入风险,易被恶意输入拖库
修复步骤
  • 将用于对比的营业时间转成TimeSpan类型(专门用于表示时间跨度,适合对比时分秒部分),从解析后的DateTime对象里取TimeOfDay属性(即当天的时分秒部分)做同类型比较
  • 补充营业结束时间的判断逻辑
  • 将拼接SQL的写法改为参数化查询,规避注入风险
  • (可选)用DateTime.TryParse替代直接Parse,兼容用户输入非法时间格式的场景,避免程序崩溃
修正后参考代码
// 解析用户输入的时间,加校验避免非法输入直接报错
if (!DateTime.TryParse(txt_Hora.Text, System.Globalization.CultureInfo.CurrentCulture, out DateTime data))
{
    MessageBox.Show("输入的时间格式不正确,请重新输入");
    return;
}

// 定义营业时间范围,示例为早9点至晚10点,可根据实际业务调整
TimeSpan openTime = new TimeSpan(9, 0, 0);
TimeSpan closeTime = new TimeSpan(22, 0, 0);

// 同类型对比判断是否在营业时间内
if (data.TimeOfDay >= openTime && data.TimeOfDay <= closeTime)
{
    // 参数化写SQL,彻底避免SQL注入
    string insertSql = @"INSERT INTO produtos_pedidos (quantidade, data_pedido, subtotal, hora) 
                         VALUES (@quantidade, @dataPedido, @subtotal, @hora)";
    using (MySqlCommand cmd = new MySqlCommand(insertSql, bdcon))
    {
        cmd.Parameters.AddWithValue("@quantidade", cmb_Quantidade.Text);
        cmd.Parameters.AddWithValue("@dataPedido", txt_Data.Text);
        cmd.Parameters.AddWithValue("@subtotal", lbl_Subtotal.Text);
        cmd.Parameters.AddWithValue("@hora", txt_Hora.Text);
        cmd.ExecuteNonQuery();
    }
    MessageBox.Show("Reservado com sucesso");
}
else
{
    MessageBox.Show("当前不在营业时间(9:00-22:00),无法提交预约");
}

补充说明:如果业务需要跨零点营业(比如营业时间是20:00到次日4:00),判断逻辑要调整为data.TimeOfDay >= openTime || data.TimeOfDay <= closeTime,不要直接照搬上面的区间判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:03:29