Básicamente solo quiero comprobar si un período de tiempo se solapa con otro. Fecha de finalización nula significa hasta el infinito. ¿Alguien puede acortar esto para mí, ya que es bastante difícil de leer a veces. Saludos¿Alguien puede simplificar este algoritmo para mí?
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;
}
}
Guau, eso es una bestia :) –
Una gran pregunta, pero ¿puedo sugerirle un nombre mejor? ¿Qué tal "manera concisa para saber si dos pares DateTime se superponen?" –
Un caso típico de 'fuerza mental bruta' es un problema al intentar/envolver todas las posibles constelaciones. La gente a menudo trata de resolver problemas de forma inmediata, en lugar de pensar realmente en el problema. La solución luego es mucho más fácil y es más probable que sea una clara idea. –