Ryan The Leach Ryan The Leach - 3 years ago 220
C# Question

How do you check if 2 OffsetDateTime lie within another 2 OffsetDateTIme?

Given an POCO Event{OffsetDateTime Start, OffsetDateTime End} and a POCO Trial {OffsetDateTime Start, OffsetDateTime End}

Where trials typical span hours, and events happen over a few seconds.

How can I test whether an Event happened within a Trial?

The Naive code that came before, used: event.Start > trial.Start && event.Start < trial.End

but converting to NodaTime those comparisons are no longer valid.

I suspect I can't without making some assumptions about how it should be converted to instants and intervals, considering both Event and Trial come from a third party library, that should probably be using timezoned types, or instants rather then OffsetDateTimes.

Answer Source

OffsetDateTime.ToInstant is unambiguous, so you could certainly just convert to Instant values. You might want to create an interval from the trial though:

Interval trial = new Interval(trial.Start.ToInstant(), trial.End.ToInstant());

if (trial.Contains(event.Start.ToInstant()) &&
    trial.Contains(event.End.ToInstant()))
{
    ...
}

One potential wrinkle of this is that the end point of an interval is exclusive... so if event.End and trial.End are the same instant, the above will not enter the if statement body.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download