JavaScript date range between date range

If you're trying to detect full containment, that is fairly easy. (Also, you don't need the explicit return true/false, because the condition is a boolean anyway. Just return it)

// Illustration:
//
// startdate                          enddate
// v                                        v
// #----------------------------------------#
//
//         #----------------------#
//         ^                      ^
//         startD              endD
return startD >= startdate && endD <= enddate;

An overlap test is slightly more complex. The following will return true if the two date ranges overlap, regardless of order.

// Need to account for the following special scenarios
//
// startdate     enddate
// v                v
// #----------------#
//
//         #----------------------#
//         ^                      ^
//         startD              endD
//
// or
//
//              startdate        enddate
//                 v                v
//                 #----------------#
//
//         #------------------#
//         ^                  ^
//       startD              endD
return (startD >= startdate && startD <= enddate) ||
       (startdate >= startD && startdate <= endD);

@Bergi's answer is probably more elegant, in that it just checks the start/end pairs of the two date ranges.


In your example, the new dates are both outside the range.

If you want to check if there is any overlap between the date ranges, use:

return (endD >= startdate && startD <= enddate);

To check if they overlap with any days, use

if (endD >= startdate && startD <= enddate)

which is equivalent to

if ( !(endD < startdate || startD > enddate)) // not one after the other