Test if a period overlaps
Shows how to test if two given time periods overlap each other.
/// <summary>
/// Tests if two given periods overlap each other.
/// </summary>
/// <param name="BS">Base period start</param>
/// <param name="BE">Base period end</param>
/// <param name="TS">Test period start</param>
/// <param name="TE">Test period end</param>
/// <returns>
/// <c>true</c> if the periods overlap; otherwise, <c>false</c>.
/// </returns>
public bool TimePeriodOverlap(DateTime BS, DateTime BE, DateTime TS, DateTime TE)
{
// More simple?
// return !((TS < BS && TE < BS) || (TS > BE && TE > BE));
// The version below, without comments
/*
return (
(TS >= BS && TS < BE) || (TE <= BE && TE > BS) || (TS <= BS && TE >= BE)
);
*/
return (
// 1. Case:
//
// TS-------TE
// BS------BE
//
// TS is after BS but before BE
(TS >= BS && TS < BE)
|| // or
// 2. Case
//
// TS-------TE
// BS---------BE
//
// TE is before BE but after BS
(TE <= BE && TE > BS)
|| // or
// 3. Case
//
// TS----------TE
// BS----BE
//
// TS is before BS and TE is after BE
(TS <= BS && TE >= BE)
);
}
Url: http://www.jonasjohn.de/snippets/csharp/time-period-overlaps.htm
Language: C# | User: ShareMySnippets | Created: Oct 16, 2013