Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime falls within the last 24 hours

Tags:

c#

I have a DateTime object that I'd like to check and see if it falls within the last 24 hours.

I did something like this but its wrong:

myDateTime > DateTime.Now.AddHours(-24) && myDateTime < DateTime.Now

where did I go wrong?

like image 593
Gully Monsta Avatar asked Mar 19 '11 22:03

Gully Monsta


2 Answers

There is nothing wrong with the code that you posted, so whatever you did wrong is somewhere else in the code.

I only see two minor flaws in the code, but they only affect corner cases:

You should avoid getting the DateTime.Now property repeatedly in the code. Its value changes, so you may get inconsistent results in some cases when the values changes from one use to the next.

To get a time interval you would usually pair one inclusive and one exclusive operator, like > and <=, or >= and <. That way you can check for intervals next to each other, like 0 - 24 hours and 24 - 28 hours, without getting a gap or an overlap.

DateTime now = DateTime.Now;
if (myDateTime > now.AddHours(-24) && myDateTime <= now)
like image 176
Guffa Avatar answered Oct 13 '22 18:10

Guffa


  1. Only get DateTime.Now once within the function - otherwise the value might change.
  2. Use <=, not <. if you check a microsecond after the time has been set, it will still be equal to DateTime.Now. I actually ran into this in production code where imports wouldn't show up in a different query that checked < because the import was too fast!

Use this code:

DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
if (myDateTime > yesterday && myDateTime <= now) {
    ...
}
like image 25
configurator Avatar answered Oct 13 '22 18:10

configurator