使用 C# 中提供的开始和结束时间跨度集进行时间重叠检查



与C# 的时间重叠:检查 2 组开始和结束日期组合而不是圈数检查?

">
  • 早上 6:00"到"下午 4:30">
  • ">
  • 上午 8:29"到"下午 4:30">
private static bool CheckOverlap(TimeSpan startDate1, TimeSpan endDate1, TimeSpan startDate2, TimeSpan endDate2)
{
//TODO: Make sure startDate is lower than EndDate
if (startDate2 < endDate1 && endDate2 > startDate1)
return true;
return false;
}

您可以创建自定义类来发送有关时间段的信息,例如:

public class TimePeriod
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public TimePeriod(DateTime start, DateTime end)
{
if( start > end)
throw new InvalidArgumentException();
Start = start;
End = end;
}
public bool Overlaps(TimePeriod tp)
{
// it's enough for one's period start or end to fall between the other's start and end to overlap
if ((Start > tp.Start && Start < tp.End ) ||
(End > tp.Start && End < tp.End) ||
(tp.Start > Start && tp.Start < End) ||
(tp.End > Start && tp.End < End) )
return true;
else
return false;
}
}

然后使用变得非常容易:

TimePeriod tp1 = new TimePeriod(dt1, dt2);
TimePeriod tp2 = new TimePeriod(dt3, dt4);
var overlaps = tp1.Overlaps(tp2);

相关内容

  • 没有找到相关文章

最新更新