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?
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)
DateTime.Now
once within the function - otherwise the value might change.<=
, 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) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With