Can anyone simplify this Algorithm for me?
Posted
by Titan
on Stack Overflow
See other posts from Stack Overflow
or by Titan
Published on 2010-04-20T01:19:05Z
Indexed on
2010/04/20
1:23 UTC
Read the original article
Hit count: 330
Basically I just want to check if one time period overlaps with another. Null end date means till infinity. Can anyone shorten this for me as its quite hard to read at times. Cheers
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;
}
}
© Stack Overflow or respective owner