user123456789
user123456789

Reputation: 2004

Checking if date is within a date range

I have a GridView and I want to change the colour of the row if the date in a column is within a certain date range.

DateTime dt = new DateTime();
if (DateTime.TryParse(c.Text, out dt))
{
    if (dt.Date >= DateTime.Now.AddDays(Mod.ValidUntilDays).Date && dt.Date <= DateTime.Now.AddDays(Mod.ValidUntilDays).Date)
     {
         e.Item.Style.Add("background-color", "#FF0303");
     }
}

So the value coming from the grid is dt.Date is equal to 23/09/2016 00:00:00 and the date range I want to check is 25/09/2016 00:00:00. Mod.ValidUntilDays just adds 5 days to Today's date.

So what I am trying to do is check is23/09/2016 00:00:00 within the 5 day range which it is but the code never goes into the if statement.

Upvotes: 3

Views: 8338

Answers (1)

ADyson
ADyson

Reputation: 61904

you are asking the date to be >= 5-days-time and <= 5-days-time. So unless it == 5-days-time it'll return false. I think you mean this:

DateTime dt = new DateTime();
if (DateTime.TryParse(c.Text, out dt))
{
  DateTime now = DateTime.Now;
  if (dt.Date >= now.Date && dt.Date <= now.AddDays(Mod.ValidUntilDays).Date)
  {
     e.Item.Style.Add("background-color", "#FF0303");
  }
}

Upvotes: 7

Related Questions