基本上我只想检查一个时间段是否与另一个时间段重叠。 空结束日期意味着无穷大。任何人都可以缩短这一点,因为它有时很难阅读。干杯任何人都可以为我简化这个算法吗?
public class TimePeriod
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Overlaps(TimePeriod other)
{
// Means it overlaps
if (other.StartDate == this.StartDate
|| other.EndDate == this.StartDate
|| other.StartDate == this.EndDate
|| other.EndDate == this.EndDate)
return true;
if(this.StartDate > other.StartDate)
{
// Negative
if (this.EndDate.HasValue)
{
if (this.EndDate.Value < other.StartDate)
return true;
if (other.EndDate.HasValue && this.EndDate.Value < other.EndDate.Value)
return true;
}
// Negative
if (other.EndDate.HasValue)
{
if (other.EndDate.Value > this.StartDate)
return true;
if (this.EndDate.HasValue && other.EndDate.Value > this.EndDate.Value)
return true;
}
else
return true;
}
else if(this.StartDate < other.StartDate)
{
// Negative
if (this.EndDate.HasValue)
{
if (this.EndDate.Value > other.StartDate)
return true;
if (other.EndDate.HasValue && this.EndDate.Value > other.EndDate.Value)
return true;
}
else
return true;
// Negative
if (other.EndDate.HasValue)
{
if (other.EndDate.Value < this.StartDate)
return true;
if (this.EndDate.HasValue && other.EndDate.Value < this.EndDate.Value)
return true;
}
}
return false;
}
}
哇,这是一个野兽:) – 2010-04-20 01:32:48
伟大的问题,但我可以建议一个更好的名字?如何“简洁的方式来判断两个DateTime对是否重叠?” – 2010-04-20 01:38:56
通过尝试/如果 - 套住所有可能的星座,一个典型的“精神强化”问题。人们通常会立即尝试解决问题,而不是真正考虑问题。解决方案然后变得更容易,更可能是一个很好的清晰的解决方案。 – 2010-04-20 01:43:50