如何在到期日前增加90天或从系统日期中减去90天

时间:2018-11-11 11:16:24

标签: c#

现在只需将90天加上有效期或从系统日期中减去90天即可。它会解决我的问题!我希望项目有效日期还剩90天时,行颜色为红色

 private void DgvStock_CellFormatting_1(object sender, DataGridViewCellFormattingEventArgs e)
        {

            foreach (DataGridViewRow row in DgvStock.Rows)
            {

                DateTime exp = Convert.ToDateTime(row.Cells["ExpDate"].Value);

                if (exp <= System.DateTime.Now)
                {
                    row.DefaultCellStyle.ForeColor = Color.White;
                    row.DefaultCellStyle.BackColor = Color.Red;
                }
            }
        }

3 个答案:

答案 0 :(得分:1)

要添加或减去当前日期的天数,您可以这样做:

var date = DateTime.Now.AddDays(-90);

FlakeIdGenerator

并更改您的代码,例如:

if (exp <= System.DateTime.Now)
{
    row.CellStyle.ForeColor = Color.White;
    row.CellStyle.BackColor = Color.Red;
}
else
{
    row.CellStyle.ForeColor = Color.Black;
    row.CellStyle.BackColor = Color.White;       // or some other origin color
}

看起来像您错误地使用了DefaultCellStyleDefaultCellStyle更改所有行的样式,但是您需要更改特定行的颜色。

答案 1 :(得分:0)

怎么样

if (exp <= System.DateTime.Now.AddDays(-90))
{
    //...

P.S:我将DateTime.Now移到循环外,并将其保存到变量一次。

答案 2 :(得分:0)

尝试一下:

   foreach (DataGridViewRow row in DgvStock.Rows)
        {
            DateTime exp = DateTime.Parse(row.Cells["ExpDate"].Value + "");


            if (exp <= System.DateTime.Today.AddDays(-90))
            {
                row.DefaultCellStyle.ForeColor = Color.White;
                row.DefaultCellStyle.BackColor = Color.Red;
            }
            else
            {

                row.DefaultCellStyle.BackColor = Color.White;
            }
        }
相关问题