【问题标题】:Cannot compare two date in while loop无法在while循环中比较两个日期
【发布时间】:2016-02-12 10:39:08
【问题描述】:

我在使用“日期”属性时遇到了问题。 我的课在这里:

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。这是图像显示错误。

更新:r["TransDT"] is object{string} in database has values: 11/11/2015 18:03:11

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

调试时出错:

Animate screenshot gif

【问题讨论】:

  • 嗯,很明显,r["TransDT"] 不是 DateTime 类型,你能验证它实际上是什么类型吗? Debug.WriteLine(r["TransDT"].GetType().FullName);(假设不能是null
  • @LasseV.Karlsen DateTime 虽然据我所知是可以为空的。因此,如果我没记错的话,如果 null 应该是 DBNULL?
  • 另外,你真的要插入行直到第二天吗?您的 while 循环不会前进r,您将一遍又一遍地做同样的事情,直到发生变化的一件事已经发生了足够的变化,那就是DateTime.Today。此外,DateTime.Today 已经只是日期,您也不需要.Date
  • 如果你真的想使用if,为什么还要使用while
  • DBNull 不是DateTime 类型,您不能将其拆箱到DateTime

标签: c# mysql ado.net


【解决方案1】:

该值可能是null(DBNull.Value),您可以尝试使用as-operator 将其转换为DateTime?。当演员阵容失败时,你会得到一个Nullable<DateTime>HasValue=false

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

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

【讨论】:

  • 你也可以这样做:if (TransDT == DateTime.Today)
  • @LasseV.Karlsen:对,我只是想让DateTime? 是什么以及它有HasValueValue 属性更清楚。否则就不清楚为什么我在这里使用它。
  • @TimSchmelter,我试过这段代码。但TransDT 的值始终为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 2023-03-14
  • 2012-01-07
  • 2015-05-19
  • 2013-06-06
  • 1970-01-01
相关资源
最近更新 更多