Home > Net >  Checking if 2 dates is within range of 2 other dates
Checking if 2 dates is within range of 2 other dates

Time:10-14

I have a booking web application where bookings store the from and to date.

When a new booking is made, I need to check if the booking from and to date is within any of the bookings from and to date.

Let's say I have a booking with:

A from date of: 10/10/2021 A to date of: 15/10/2021

If I try to make a new booking with:

A from date of: 09/10/2021 A to date of: 16/10/2021

Then it should return false

Or if I try to make a new booking with:

A from date of: 10/10/2021 A to date of 11/10/2021

Then it should return false.

So far this is what I have:

var bookings = _bookingRepository.GetAll().Where(oldBooking => newBookingfrom >= oldBooking.From && newBookingTo <= oldBooking.To);

But this doesn't work as expected, this seemed quite easy when I first approached it but heck it's confusing me.

FYI: The GetAll() method returns all of the bookings from the DB.

CodePudding user response:

To check if an interval overlaps another, you need to compare one end-point against the other start-point, and vice-versa.

var bookings = _bookingRepository.GetAll()
    .Where(oldBooking =>
        newBookingfrom < oldBooking.To &&
        newBookingTo > oldBooking.From );

To get results which don't overlap, just add !( over the whole condition.

Note that depending on whether you have a time component involved, you may need to change the conditions to >=.

CodePudding user response:

I would suggest using this query, it will return true if the time range is not overlapping else it will return false.

var bookings = _bookingRepository.GetAll()
    .Where(oldBooking =>
        newBookingfrom > oldBooking.To ||
        newBookingTo < oldBooking.From );

Here I am assuming that you are already checking that newBookingfrom is always before newBookingTo and date range is database also is correct range.

  • Related