简体   繁体   English

比较两个日期,一个来自数据库,另一个来自datetime.now

[英]Comparing two dates one from the database and datetime.now

I have a gridview and I would like to highlight the days which has difference > 10. 我有一个gridview,我想强调一下相差> 10的日子。

What I have now 我现在有什么

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
            }
        }
    }

Date format of the one saved onto my database is dd-MM-YYYY and it is saved as nvarchar. 保存到我的数据库中的日期格式为dd-MM-YYYY,并保存为nvarchar。

您应该这样解析DateTime:

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

Victor Leontyev is right on with the parsing. Victor Leontyev的解析正确。 But then you also have to tweak you logic: 但随后您还必须调整逻辑:

if (difference.TotalDays > 0)

to

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

Use this: 用这个:

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

or days 或天

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

Or seconds, miliSeconds, Weeks, .... 或秒,miliSeconds,周....

To get date from your string do this: 要从字符串中获取日期,请执行以下操作:

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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM