比较数据库和datetime.now中的两个日期

时间:2017-02-05 16:04:03

标签: c# asp.net

我有一个gridview,我想强调那些有差异的日子> 10。

我现在拥有什么

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DateTime dateNow = DateTime.Now;
            string dateCreated = e.Row.Cells[5].Text;

            DateTime dc = Convert.ToDateTime(dateCreated);
            TimeSpan difference = dateNow - dc;

            if (difference.TotalDays > 0)
            {
                e.Row.BackColor = System.Drawing.Color.Cyan; // This will make row back color red
            }
        }
    }

保存在我的数据库中的日期格式为dd-MM-YYYY,并保存为nvarchar。

3 个答案:

答案 0 :(得分:0)

您应该像这样解析DateTime:

DateTime dc = DateTime.ParseExact(dateCreated, "dd-MM-yyyy", CultureInfo.InvariantCulture);

答案 1 :(得分:0)

Victor Leontyev正在进行解析。但是你还必须调整逻辑:

if (difference.TotalDays > 0)

if (Math.Abs(difference.TotalDays) > 10)

答案 2 :(得分:0)

使用此:

int minutes = (int)DateTime.Now.Subtract(dc).TotalMinutes;

或天

int days = (int)DateTime.Now.Subtract(dc).TotalDays;

或秒,miliSeconds,Weeks,....

要从字符串中获取日期,请执行以下操作:

string dateCreated = "01-01-2017";
string[] dcArray = dateCreated.Split('-');
DateTime dc = new DateTime(int.Parse(dcArray[2]), int.Parse(dcArray[1]), int.Parse(dcArray[0]));