在while循环中无法比较两个日期

时间:2015-11-11 10:42:16

标签: c# mysql ado.net

使用“Date”属性时遇到问题。 我的班级在这里:

public bool ChuyenDSChamCong()
{
    try
    {
        DataTable dta = DSChamCong();
        if (dta == null)
            return false;
        foreach (DataRow r in dta.Rows)
        {
            try
            {
                string sql = "delete FROM tk_dlchamcong where MD5(CONCAT(ma_chamcong,ma_nv, tg_check)) = md5('" + r["CardID"] + r["StaffID"] + r["TransDT"].ToString() + "')";
                MYSQLDB.query(sql);
                while (((DateTime)r["TransDT"]).Date == (DateTime.Today).Date)
                {
                    string sql1 = "INSERT INTO tk_dlchamcong(ID,ma_chamcong, ma_nv, tg_check)values(md5('" + r["CardID"] + r["StaffID"] + r["TransDT"].ToString() + "'),'" + r["CardID"] + "', '" + r["StaffID"] + "', '" + r["TransDT"] + "')";
                    MYSQLDB.query(sql1);
                }
            }
            catch {
            }
        }
        return true;
    }
    catch { }
    return false;
}

我不能使用Date()属性,它只接受Date。但是当我调试它时会显示这样并跳转以捕获错误。

无法比较,r["TransDT"]DateTime。这是图像显示错误。

enter image description here

更新:r [“TransDT”]是数据库中的对象{string}具有值:11/11/2015 18:03:11

我的格式是这样的查询,如: FORMAT(TransDT,'dd/MM/yyyy HH:mm:ss') as TransDT from Transact

调试时出错:

Animate screenshot gif

1 个答案:

答案 0 :(得分:0)

值可以是nullDBNull.Value),您可以尝试使用as-operator将其投放到DateTime?。当演员表失败时,您会获得Nullable<DateTime> HasValue=false

DateTime? TransDT = r["TransDT"] as DateTime?;
if(TransDT.HasValue && TransDT.Value.Date == DateTime.Today)
{
    // ...
}

您不需要whileif已足够,因为您只有一个DataRow