71

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.

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178
  • 1
    Sounds like you need to do the comparison as part of your database query and not in C# – Andrew Savinykh Apr 15 '11 at 05:54
  • 1
    @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? – Deeptechtons Apr 15 '11 at 06:04
  • 1
    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; – VikciaR Apr 15 '11 at 06:15

5 Answers5

109

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
}  
Jason Slocomb
  • 3,030
  • 1
  • 23
  • 25
  • 7
    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. – VikciaR Apr 15 '11 at 07:17
  • 16
    -1 This is a more obscure way of getting the wrong answer - it's `targetDt < d1`, just messier. – Kirk Broadhurst Jul 11 '12 at 04:24
  • 2
    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. – Bitterblue Jun 27 '18 at 09:37
  • 1
    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 docs](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netcore-3.1) – Cícero Neves May 15 '20 at 17:13
64

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
Ermiya Eskandary
  • 15,323
  • 3
  • 31
  • 44
VikciaR
  • 3,324
  • 20
  • 32
  • @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 5Pm – Deeptechtons Apr 15 '11 at 06:00
  • 1
    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. – VikciaR Apr 15 '11 at 06:04
  • Vikcia's got it, this is probably the cleanest way to do this. – Matt Greer Apr 15 '11 at 06:09
  • 2
    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. – Ian Mercer Apr 15 '11 at 06:19
  • You are right, Hightechrider. But this is details - you can express this with if (B – VikciaR Apr 15 '11 at 06:26
  • 1
    @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 start – Deeptechtons Apr 15 '11 at 06:42
  • @Deeptechtons 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 posted – Cícero Neves May 15 '20 at 17:16
15

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

bmeredith
  • 655
  • 6
  • 8
Wayne Hamberg
  • 155
  • 1
  • 3
1

You can, use:

if (date >= startDate && date<= EndDate) { return true; }
xiawi
  • 1,772
  • 4
  • 19
  • 21
ynth
  • 11
  • 2
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
}
KaeL
  • 3,639
  • 2
  • 28
  • 56
  • 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 it – Deeptechtons Apr 15 '11 at 06:06