Question

Given multiple time ranges, i need to find out which time range does the current time belong to. How can I do this more efficiently ignoring the date part of the DateTime.

TimeSlot.Overlaps(DateTime currTime) method should ignore the date part and match only time part of it.

Was it helpful?

Solution

public class TimeSlot
{
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }


    public bool Overlaps(DateTime compareTime)
    {
        return Overlaps(new TimeSlot() { StartTime = compareTime, EndTime = compareTime });
    }

    public bool Overlaps(TimeSlot compareSlot)
    {
        return (
            (compareSlot.StartTime.TimeOfDay >= StartTime.TimeOfDay && compareSlot.StartTime.TimeOfDay < EndTime.TimeOfDay) ||
            (compareSlot.EndTime.TimeOfDay <= EndTime.TimeOfDay && compareSlot.EndTime.TimeOfDay > StartTime.TimeOfDay) ||
            (compareSlot.StartTime.TimeOfDay <= StartTime.TimeOfDay && compareSlot.EndTime.TimeOfDay >= EndTime.TimeOfDay)
        );
    }
}

OTHER TIPS

I would use the datediff method in .Net. You can specify which part of the date you wish to use as the interval. So, first you probably want to test that they are within the same day. Specify day as the interval. The result should be zero. Then you can find hours, minutes, seconds, etc. I'm pretty sure it gives you the fractional parts: 1 hour, 45 min versus 1.75 hours 105 min. Then just compare the start and end datetimes in your TimeSlot class (which I'm guessing is custom?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top