Date Range Overlap with Nullable Dates

前端 未结 4 1616
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 03:23

I\'m looking for an extended answer to the question asked here:

Determine Whether Two Date Ranges Overlap

where any of the dates in either date range can be null

4条回答
  •  有刺的猬
    2021-02-10 04:02

    Without considering nulls, answer is

    (StartA <= EndB) and (EndA >= StartB) (see this for detailed explanation)

    considering nulls for start and end dates,
    Using C Ternary operator syntax:
    (StartA != null? StartA: EndB <= EndB != null? EndB: StartA) && (EndA != null? EndA: StartB >= StartB != null? StartB: EndA)

    Or C# 4.x style null operators:

    (StartA??EndB <= EndB??StartA) && (EndA??StartB >= StartB??EndA)

    or in SQL:

    (Coalesce(StartA, EndB) <= Coalesce(EndB, StartA)) And (Coalesce(EndA, StartB ) <= Coalesce(StartB , EndA))

    Explanation:
    consider the non-null answer:
    (StartA <= EndB) and (EndA >= StartB)

    Now, consider that StartA is null, indicating that date range A has existed since beginning of time (BOT). In that case, DateRangeB can never be before DateRangeA. So first condition, (StartA(BOT) <= EndB) will ALWAYS be true, no matter what EndB is. So change this expression so that instead of comparing null with EndB, when StartA is null, compare EndB with itself No matter what EndB is, the expression EndB <= EndB will be true. (We could create variables to represent BOT and EOT, but this is easier).

    Do the same for other three input variables.

提交回复
热议问题