Check if datetime instance falls in between other two datetime objects
Asked Answered
S

5

75

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.

Shockey answered 15/4, 2011 at 5:49 Comment(3)
Sounds like you need to do the comparison as part of your database query and not in C#Whacky
@Zespri more details to explain the exact situation. Employee time sheet has work timings of the employee in and out time[these are customer support] and these people have fields like contact via mail, contact via phone i.e methods of communication. When someone calls with a problem then i need to check which line of communication is available for the employee at that given time[time when client calls the company customer support] understood?Shockey
You can use in database column with type Time and in c# TimeSpan class. Then is very simple select needed users: Select * from users where workStarts > @now and workEnds < @now;Goolsby
S
113

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
}  
Swetiana answered 15/4, 2011 at 6:17 Comment(4)
Is it right answer? DateTime.Ticks is the number of ticks that represent the date and time of this instance. The value is between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks. So, you will compare full date and not time.Goolsby
-1 This is a more obscure way of getting the wrong answer - it's targetDt < d1, just messier.Binns
It will work since DateTime is internally a simple number. When you parse it, it is converted into that number. Every instance of DateTime is that number with different values. But you can also compare DateTime because it implements IComparable interface. SImply remove all the Ticks in this answer.Chlodwig
how was this accepted as the right answer? doing the way suggested here will still take into account the date component of the DateTime object which is not what the OP wants They want to just take into account the time component, no date. "Gets the number of ticks that represent the date and time of this instance." MS docsBalenciaga
G
65

Do simple compare > and <.

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

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something
Goolsby answered 15/4, 2011 at 5:55 Comment(7)
@Vikcian doesn't this also account for the day. example dt1 = 1/1/2011 1:00:00Am and dt2 = 1/1/2011 5:00:00 Pm and checked time 10/2/2011 2:00:00 Am then this would return false even though the time 2:00Am falls in between 1Am and 5PmShockey
From MSDN: DateTime.TimeOfDay Property - A time interval that represents the fraction of the day that has elapsed since midnight. So, when you compare two dates TimeOfDay you will get what you wanted - which time was earlier/later.Goolsby
Vikcia's got it, this is probably the cleanest way to do this.Harder
It works provided there are no night shift workers. But if B=11PM and C=5AM...?? ... question isn't clear on whether that could happen.Qianaqibla
You are right, Hightechrider. But this is details - you can express this with if (B<C) then it's not night shift worker else - night shift worker.Goolsby
@Vikcia Answered by Jason elegant solution without must fuss and gives the answer for all values of input. But thanks for giving me a good startShockey
@Shockey the answer given by Jason takes into account the date component of the DateTime object. You said you are only interested in the time component of it. Why did you accept it was the correct answer? This should be the correct one, if one is to read the question you postedBalenciaga
M
18

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(,,));

Meneses answered 15/2, 2019 at 16:29 Comment(1)
I guess should be dt > start instead of dt >= start.Gantry
V
1

You can, use:

if (date >= startDate && date<= EndDate) { return true; }
Vergos answered 6/9, 2019 at 8:17 Comment(1)
This is the same as the answer of @GoolsbyManifestation
G
0

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
}
Govan answered 15/4, 2011 at 6:3 Comment(1)
doesn't this account even the date part. I am least bothered on date part .Time is all that matters to me. Why i stress on this is that at the time of registration the staff/customer support guy of the company just provides the timeslot he is free to attend to any clients. But the date is padded dummy'ly just because the datetime field in Db needs itShockey

© 2022 - 2024 — McMap. All rights reserved.