Reputation: 27
I want to check if a given period of time(HH:MM) is within the other one and return true else it shall return false
I have tried this equation
(StartTime_1 <= EndTime_2 && StartTime_2 < EndTime_1) ||
(StartTime_1 < StartTime_2 && EndTime_2 <= EndTime_1)
But it seems to measure overlapping rather than any thing, what i want is like this, For example Start_1 is 08:00 AM and End_1 is 10:00 PM, any time that comes between these two it shall return true and any other like (from 09 PM to 08 AM) it shall return false.
Upvotes: 1
Views: 376
Reputation: 4114
With this method, I can check if a period (start2 to end2) is contained in another (start1 to end1)
public static Boolean IsContained(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
{
// convert all DateTime to Int
Int32 start1_int = start1.Hour * 60 + start1.Minute;
Int32 end1_int = end1.Hour * 60 + end1.Minute;
Int32 start2_int = start2.Hour * 60 + start2.Minute;
Int32 end2_int = end2.Hour * 60 + end2.Minute;
// add 24H if end is past midnight
if (end1_int <= start1_int)
{
end1_int += 24 * 60;
}
if (end2_int <= start2_int)
{
end2_int += 24 * 60;
}
return (start1_int <= start2_int && end1_int >= end2_int);
}
Upvotes: 0
Reputation: 18877
There are a number of possible cases.
To check if they overlap at any point in time, you need to check if the end of the test time period start is before time period 1 end, and if the test time end is after period 1 start.
If you have a different description of overlap, you'll have to expand by referencing which lines in the image should be considered in or out.
Upvotes: 3
Reputation: 1976
How about
(StartTime_2 >= StartTime_1 && EndTime_2 <= EndTime_1) && (StartTime_1 < EndTime_1) && (StartTime_2 < EndTime_2)
I would think this should do what you're looking for
Upvotes: 0
Reputation: 61379
Its hard to tell from your variable names, but it looks like you almost have it right. To test for true containment, you just need to always use "and" (&&
):
DateTime AllowedStart;
DateTime AllowedEnd;
DateTime ActualStart;
DateTime ActualEnd;
//Obviously you should populate those before this check!
if (ActualStart > AllowedStart && //Check the start time
ActualStart < AllowedEnd && //Technically not necessary if ActualEnd > ActualStart
ActualEnd < AllowedEnd && //Check the end time
ActualEnd > AllowedStart) //Technically not necessary if ActualEnd > ActualStart
Upvotes: 0