user2818430 user2818430 - 18 hours ago 5
C# Question

c# check if a timespan range is between timespan range and how many hours

Assuming I have 3 time ranges:

07:00 - 18:00
18:00 - 23:00
23:00 - 07:00


and the code:

public class TimeShift
{
public TimeSpan Start { get; set; }
public TimeSpan End { get; set; }
}

List<TimeShift> shifts = new List<TimeShift>();


How can I check if every item in the list is between the 3 ranges above and how many hours?

For example one
TimeShift
where:

Start: 07:00
End: 23:30


then that means 16.5 hours.

For the examples above:

Range 1: 11 hours
Range 2: 5 hours
Range 3: 0.5 hours

Answer

Here is a solution including tests:

Calc

public class TimeSpacCalculator
{
    public static TimeSpan GetTimeSpanIntersect(TimeShift input, TimeSpan start, TimeSpan end)
    {
        // Loopsback from 23:59 - 00:00
        if (start > end)
            return GetTimeSpanIntersect(input, new TimeSpan(), end) +
                   GetTimeSpanIntersect(input, start, TimeSpan.FromHours(24));

        if (input.End < start)
            return new TimeSpan();

        if (input.Start > end)
            return new TimeSpan();

        var actualStart = input.Start < start
            ? start
            : input.Start;

        var actualEnd = input.End > end
            ? end
            : input.End;

        return actualEnd - actualStart;
    }
}

Classes

public class TimeRange : TimeShift
{
    public TimeRange(string name, TimeSpan start, TimeSpan end) : base(start, end)
    {
        Name = name;
    }

    public string Name { get; set; }
}

public class TimeShift
{
    public TimeShift(TimeSpan start, TimeSpan end)
    {
        Start = start;
        End = end;
    }

    public TimeSpan Start { get; set; }
    public TimeSpan End { get; set; }
}

Tests

[TestFixture]
internal class TimShiftTests
{
    [Test]
    public void Test()
    {
        var ranges = new List<TimeRange>
        {
            new TimeRange("Range1", TimeSpan.FromHours(7), TimeSpan.FromHours(18)),
            new TimeRange("Range2", TimeSpan.FromHours(18), TimeSpan.FromHours(23)),
            new TimeRange("Range3", TimeSpan.FromHours(23), TimeSpan.FromHours(7))
        };

        var input = new TimeShift(TimeSpan.FromHours(7), new TimeSpan(23, 30, 0));

        var result = new Dictionary<string, TimeSpan>();

        foreach (var range in ranges)
        {
            var time = TimeSpacCalculator.GetTimeSpanIntersect(input, range.Start, range.End);

            result.Add(range.Name, time);

            Console.WriteLine($"{range.Name}: " + time.TotalHours);
        }

        result["Range1"].Should().Be(TimeSpan.FromHours(11));
        result["Range2"].Should().Be(TimeSpan.FromHours(5));
        result["Range3"].Should().Be(TimeSpan.FromHours(0.5));
    }
}
Comments