Ryan Leach
Ryan Leach

Reputation: 4470

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.

Upvotes: 0

Views: 209

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500795

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.

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241563

I could be wrong, but it seems you were wanting to know if the trial and the event overlapped. Assuming that your ranges are half-open intervals (inclusive start, exclusive end) - then you would test for overlap with:

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

Upvotes: 1

Related Questions