Home > Blockchain >  C# Linq: check if two datetime values are between two other datetime values
C# Linq: check if two datetime values are between two other datetime values

Time:07-22

I have a scenario where a filter has a fromDate and toDate, showing objects that have a startDate and an endDate.

I woud like to use linq to check if the period between startDate and endDate is within startDate and endDate for the objects.

If fromDate is 10.10.2022 00:00 and toDate is 20.10.2022 00:00 (The filter)

Then following objects should be shown:

  • startDate 09.10.2022 00:00 - endDate 11.10.2022 00:00 (Just within fromDate)
  • startDate 11.10.2022 00:00 - endDate 15.10.2022 00:00 (Within fromDate and toDate)
  • startDate 19.10.2022 00:00 - endDate 21.10.2022 00:00 (Just within toDate)

I can't seem to get it correct for all scenarios, any help appreciated.

CodePudding user response:

This should do the job:

public bool Intersects(DateTime startDate1, DateTime endDate1, DateTime startDate2, DateTime endDate2)
{
    return (startDate2 > startDate1 && startDate2 < endDate1) ||
    (endDate2 > startDate1 && endDate2 < endDate1) ||
    (startDate2 < startDate1 && endDate2 > endDate1);
}

CodePudding user response:

Dates can overlap different ways

enter image description here

  • Related