c# Match shift that spans over midnight

666 Views Asked by At

I have the following netfiddle:

.net fiddle

How can I make it work by adding a period that spans over midnight like this:

`new Period( "9", Days.Workdays, TimeSpan.FromHours(22), TimeSpan.FromHours(07) )`

Notice from 22:00 (10:00 PM) to 07:00 (07:00 AM)

2

There are 2 best solutions below

0
On

Matt has the right answer above, but a couple changes:

First, you need to make sure you have parentheses (hence your memory problem):

var period = _periods.Where(e => e.Days.HasFlag(day) && (e.Start <= e.End ? (e.Start <= timeOfDay && e.End > timeOfDay) : (e.Start <= timeOfDay || e.End > timeOfDay))).FirstOrDefault();

Second, in your GetShiftPeriods method, you need to shift by a day (simply adding period.End won't work in this scenario because that would just be "7hrs" instead of 7 in the morning.

        var next = current.Date + period.End;
        if (period.End < period.Start)
        {
            next = next.AddDays(1);
        }

Lastly, you have some overlap in your periods that you've defined. It works fine for me when I remove period #4 (comment out) with the two changes above. Not sure if you intended to have overlap, but if you do - that period will be ignored.

6
On

Assuming your question is about this part of your code:

e.Start <= timeOfDay && e.End > timeOfDay

You can change that to the following to account for time ranges over midnight:

e.Start <= e.End                                   // Are times in sequence?
    ? (e.Start <= timeOfDay && e.End > timeOfDay)  // Yes - standard calculation (AND)
    : (e.Start <= timeOfDay || e.End > timeOfDay)  // No - inverse calculation (OR)