I’m currently working on a project where I need to determine whether two shifts overlap in C#. Each shift is represented by a ShiftType class, containing start and end hours.
Here’s an example of the ShiftType class:
public class ShiftType
{
public string Id { get; set; }
public int StartHour { get; set; }
public int EndHour { get; set; }
}
I need to write a method that checks if two shifts overlap. For instance, if shift A starts at 6 and ends at 14, and shift B starts at 14 and ends at 22, they don’t overlap. However, if shift C starts at 22 and ends at 7 (crosses midnight), it overlaps with shift A because it extends into the next day.
I’ve attempted to implement a method using comparisons of start and end hours, but I’m struggling to handle cases where one shift extends into the next day. How can I properly implement this functionality to accurately determine if two shifts overlap?
Any guidance or code examples would be greatly appreciated. Thank you!
Gergő Sillye is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You could add this method to your class (not tested yet but should work):
public bool OverlapsWith(ShiftType other)
{
bool thisIsNightShift = StartHour > EndHour;
bool otherIsNightShift = other.StartHour > other.EndHour;
if (!thisIsNightShift && !otherIsNightShift)
{
return StartHour < other.EndHour && EndHour > other.StartHour;
}
else if (thisIsNightShift && otherIsNightShift)
{
return StartHour < other.EndHour && EndHour > other.StartHour;
}
else if (thisIsNightShift)
{
return StartHour < other.EndHour || EndHour > other.StartHour;
}
else // otherIsNightShift
{
return StartHour < other.EndHour || EndHour > other.StartHour;
}
}