Gully Monsta
Gully Monsta

Reputation: 233

C# DateTime falls within the last 24 hours

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?

Upvotes: 23

Views: 33371

Answers (3)

j4jada
j4jada

Reputation: 722

Learning from both the above answers and also to improve the readability of the code we can use a method like this.

using System;

public class Program
{
    public static void Main()
    {
            
        DateTime myDateTime = DateTime.Parse("2021-08-25T20:20:19.5540211");
        DateTime now = DateTime.Now;
        DateTime yesterday = now.AddHours(-24);
        
        if (IsBewteenTwoDates(myDateTime, yesterday, now))
        {
            Console.WriteLine("this date ({0}) is between {1} & {2}", myDateTime, yesterday, now);
        }
        else
        {
            Console.WriteLine("this date ({0}) is not between {1} & {2}", myDateTime, yesterday, now);
        }   
    }
    
    // Checks if the DateTime object dt is between start and end DateTime.
    public static bool IsBewteenTwoDates(DateTime dt, DateTime start, DateTime end)
    {
        return dt >= start && dt <= end;
    }
}

Check the fiddle here.

Upvotes: 0

Guffa
Guffa

Reputation: 700222

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)

Upvotes: 47

configurator
configurator

Reputation: 41620

  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) {
    ...
}

Upvotes: 13

Related Questions