Check if datetime instance falls in between other two datetime objects

C#asp.netDatetimeTimespan

C# Problem Overview


I would like to know a simple algorithm to check if the given instance of datetime lies between another two instances in C#.

Note:

I skimmed though this https://stackoverflow.com/questions/2634127/how-do-i-check-if-a-given-datetime-object-is-between-two-datetimes and it was for python and many more for php. Most of the other questions were regarding difference between the two.

Details:

I am more specific about the time, date does not matter to me. For example i got DataBase entry for a staff who works between 10:00 Am - 9:00 Pm and I would like to know which staff is engaged in class at the given time like 2:00 Pm. Now this would return me the staff's details who are engaged at this time.

Edit

After accepting the answer(been more than year back), i realized i had incorrectly described the problem. But all i think that was to be done back then was to do date and time comparison. So answers by both Jason and VikciaR work.

C# Solutions


Solution 1 - C#

DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.

// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
    // targetDt is in between d1 and d2
}  

Solution 2 - C#

Do simple compare > and <.

if (dateA>dateB && dateA<dateC)
    //do something

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something

Solution 3 - C#

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

Solution 4 - C#

You can use:

if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
{
   //do code here
}

or

if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
{
   //do code here
}

Solution 5 - C#

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeeptechtonsView Question on Stackoverflow
Solution 1 - C#Jason SlocombView Answer on Stackoverflow
Solution 2 - C#VikciaRView Answer on Stackoverflow
Solution 3 - C#Wayne HambergView Answer on Stackoverflow
Solution 4 - C#KaeLView Answer on Stackoverflow
Solution 5 - C#ynthView Answer on Stackoverflow