用当前日期在gridview中查找datetime列的更大日期

本文关键字:日期 datetime 查找 当前日期 gridview | 更新日期: 2023-09-27 18:04:45

我有一个gridview,以及MM/dd/yyyy格式的日期列。如果日期小于当前日期,我需要突出显示gridview中的行。

我的代码是,

 protected void grdAssignment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string curDate = DateTime.Now.ToString("MM'/'dd'/'yyyy");
                if (e.Row.Cells[2].Text < Convert.ToString(curDate))
                {
                   //color code
                }
        }
}

错误:字符串未被识别为有效的日期时间。

用当前日期在gridview中查找datetime列的更大日期

try
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DateTime dtRow = DateTime.ParseExact(e.Row.Cells[2].Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            DateTime curDate = DateTime.Now;
            int result = DateTime.Compare(dtRow, curDate);
            if ( result < 0 )
            {
               //color code
            }
    }

备注:使用CultureInfo.InvariantCulture需要添加using System.Globalization;

试试这个

if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DateTime curDate = DateTime.Now
            if (Convert.ToDateTime(e.Row.Cells[2].Text) < curDate)
            {
               //color code
            }
    }

为了避免错误,使用TryParse

if (e.Row.RowType == DataControlRowType.DataRow)
{
            DateTime dt;
            if (DateTime.TryParse(e.Rows.Cells(2).Text, out dt))
            {
                if (dt < DateTime.Now)
                {
                    //color code
                }
            }
}