Issaki
Issaki

Reputation: 1064

Check for Date overlapping where end date might be null

I am currently trying to check for date overlapping where the end date might be null. With my current code, I am able display the conflict message if scenario 1 occurs. However, I am unable to display the conflict message for scenario 2. For example,

Scenario 1: End date not null

1/7/2018 to 1/9/2018

1/6/2018 to 1/9/2018

Result: there is conflict

Scenario 2: End date is null

1/7/2018 to null

1/6/2018 to 1/9/2018

Result: There is conflict

Here are my codes:

if ((A.StartDate < B.EndDate) && 
    (B.StartDate < A.EndDate)) {
   Console.WriteLine("Conflict");
}

Upvotes: 0

Views: 726

Answers (1)

Richard
Richard

Reputation: 108975

Assuming that EndDate being null is essentially "no end date", so any date is always before this.

You can make use of the null object pattern, replacing null with a suitable always matching instance (and the easiest way to do that is to use the null-coalescing operator).

var ed = A.EndDate ?? DateTime.MaxValue;

if (theDate < ed) {
  // We're in range
}

Upvotes: 4

Related Questions