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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.Nowproperty 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.