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.

Jon Skeet
people
quotationmark

Note: this answer aims at "trial completely contains event" - for "trial overlaps event", see Matt Johnson's answer.

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.

people

See more on this question at Stackoverflow