Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if datetime instance falls in between other two datetime objects

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 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.

like image 929
Deeptechtons Avatar asked Apr 15 '11 05:04

Deeptechtons


People also ask

How do you find the date between two dates?

To check if a date is between two dates:Use the Date() constructor to convert the dates to Date objects. Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.

How do you check if a time is between two times in python?

Datetime objects are comparable, so you can compare datetime objects using the < , > , <= , >= , and == comparison operators. Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.


1 Answers

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 }   
like image 166
Jason Slocomb Avatar answered Oct 06 '22 00:10

Jason Slocomb