试试这个。此方法将确定(两个)日期跨度是否重叠,而不考虑方法输入参数的顺序。这也可以用于两个以上的日期跨度,通过单独检查每个日期跨度组合(例如,有3个日期跨度,对span2运行span1,对span3运行span2,对span3运行span1):
public static class HelperFunctions
{
public static bool AreSpansOverlapping(Tuple<DateTime,DateTime> span1, Tuple<DateTime,DateTime> span2, bool includeEndPoints)
{
if (span1 == null || span2 == null)
{
return false;
}
else if ((new DateTime[] { span1.Item1, span1.Item2, span2.Item1, span2.Item2 }).Any(v => v == DateTime.MinValue))
{
return false;
}
else
{
if (span1.Item1 > span1.Item2)
{
span1 = new Tuple<DateTime, DateTime>(span1.Item2, span1.Item1);
}
if (span2.Item1 > span2.Item2)
{
span2 = new Tuple<DateTime, DateTime>(span2.Item2, span2.Item1);
}
if (includeEndPoints)
{
return
((
(span1.Item1 <= span2.Item1 && span1.Item2 >= span2.Item1)
|| (span1.Item1 <= span2.Item2 && span1.Item2 >= span2.Item2)
) || (
(span2.Item1 <= span1.Item1 && span2.Item2 >= span1.Item1)
|| (span2.Item1 <= span1.Item2 && span2.Item2 >= span1.Item2)
));
}
else
{
return
((
(span1.Item1 < span2.Item1 && span1.Item2 > span2.Item1)
|| (span1.Item1 < span2.Item2 && span1.Item2 > span2.Item2)
) || (
(span2.Item1 < span1.Item1 && span2.Item2 > span1.Item1)
|| (span2.Item1 < span1.Item2 && span2.Item2 > span1.Item2)
) || (
span1.Item1 == span2.Item1 && span1.Item2 == span2.Item2
));
}
}
}
}
测试:
static void Main(string[] args)
{
Random r = new Random();
DateTime d1;
DateTime d2;
DateTime d3;
DateTime d4;
for (int i = 0; i < 100; i++)
{
d1 = new DateTime(2012,1, r.Next(1,31));
d2 = new DateTime(2012,1, r.Next(1,31));
d3 = new DateTime(2012,1, r.Next(1,31));
d4 = new DateTime(2012,1, r.Next(1,31));
Console.WriteLine("span1 = " + d1.ToShortDateString() + " to " + d2.ToShortDateString());
Console.WriteLine("span2 = " + d3.ToShortDateString() + " to " + d4.ToShortDateString());
Console.Write("\t");
Console.WriteLine(HelperFunctions.AreSpansOverlapping(
new Tuple<DateTime, DateTime>(d1, d2),
new Tuple<DateTime, DateTime>(d3, d4),
true //or use False, to ignore span's endpoints
).ToString());
Console.WriteLine();
}
Console.WriteLine("COMPLETE");
System.Console.ReadKey();
}