//片段1
public static bool IsOverlapping(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
{
if (start2 >= start1 && start2 <= end1 || end2 >= start1 && end2 <= end1)
{
return true;
}
else
{
return false;
}
}
//片段2
public static bool IsOverlapping(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
{
if (start1 == start2 || end1 == end2)
{
return true;
}
DateTime[] array = new DateTime[] { start1, end1, start2, end2 };
int[] indices = Enumerable.Range(0, 4).ToArray();
Array.Sort(array, indices);
return indices[1] - indices[0] != 1 && indices[3] - indices[2] != 1 && array[indices[1]] != array[indices[2]];
}
1 好一些。
不过可以再改进一下。
public static bool IsOverlapping(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
{
return IsInRange(start1, end1, start2) || IsInRange(start1, end1, end2);
}
public static bool IsInRange(DateTime start, DateTime end, DateTime x)
{
return x >= start && x <= end;
}
再进一步可以把DateTime start, DateTime end定义成一个元组。
public static bool IsOverlapping((DateTime start, DateTime end) range1, (DateTime start, DateTime end) range2)
{
return IsInRange(range2.start, range1) || IsInRange(range2.end, range1);
}
public static bool IsInRange(DateTime x, (DateTime start, DateTime end) range)
{
return x >= range.start && x <= range.end;
}
再进一步可以提取一个类型
public struct DateTimeRange
{
public DateTime Start { get; }
public DateTime End { get; }
public DateTimeRange(DateTime start, DateTime end)
{
this.Start = start;
this.End = end;
}
public bool IsIn(DateTime value)
{
return value >= Start && value <= end;
}
public bool IsOverlapping(DateTimeRange other)
{
return IsIn(other.Start) || IsIn(other.End);
}
}
你是要判断两段时间有重叠吗?我觉得这样判断比较清楚:找不重叠的情况的补集:
bool FuckMe(start1, end1, start2, end2){
return !(end2 < start1 || start2 > end1)
}
这个是要判断2个是时间范围
t1=s1~e1
t2=s2~e2
t2包含在t1段内;
必然是方法1更好吧,逻辑清晰点,方法二太绕了,效率也低!