check date within last 7 days

  • Thread starter Thread starter Mike P
  • Start date Start date
Mike said:
How would I check a datetime variable is within the last 7 days?

DateTime dt = ...; // the one you want to check

if (dt >= DateTime.Now.AddDays(-7))
{
}

this will rewind the clock 7 days back and check if "dt" is that point
in time, or after it.

However, if the current time of day is mid-day (12:00), and you want the
dt to be in the last 7 "days", where you include the whole day, then you
need to first get a DateTime value within that day 7 days back, and then
rewind the time to midnight.

DateTime dt7 = DateTime.Now.AddDays(-7);
dt7 = new DateTime(dt7.Year, dt7.Month, dt7.Day, 0, 0, 0);
if (dt >= dt7)
{
}
 
DateTime dt = ...; // the one you want to check

if (dt >= DateTime.Now.AddDays(-7))
{

}

this will rewind the clock 7 days back and check if "dt" is that point
in time, or after it.

However, if the current time of day is mid-day (12:00), and you want the
dt to be in the last 7 "days", where you include the whole day, then you
need to first get a DateTime value within that day 7 days back, and then
rewind the time to midnight.

DateTime dt7 = DateTime.Now.AddDays(-7);
dt7 = new DateTime(dt7.Year, dt7.Month, dt7.Day, 0, 0, 0);
if (dt >= dt7)
{

}

I think that you could do the same using DateTime.Today instead of
DateTime.Now
 
Mike said:
How would I check a datetime variable is within the last 7 days?

Maybe the code will be like this:

public static bool IsDateWithin7Days(DateTime dtToCheck) {
DateTime last7Days = DateTime.Now.AddDays(-7);
return (last7Days <= dtToCheck);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top