I'm trying to have an IF check to see if X date range is between Y date range. But it's not returning the correct true/false on the correct time:
var startdate = new Date('06/06/2013');
var enddate = new Date('06/25/2013');
var startD = new Date('06/08/2013');
var endD = new Date('06/18/2013');
if(startD >= startdate || endD <= enddate) {
return true;
} else {
return false;
}
This works, but if I change startdate
to 06/09/2013
and enddate
to 06/17/2013
it no longer works while it should work.
It should even work if startdate
was 06/07/2013
and enddate
was 06/15/2013
, but doesn't. Any thoughts?
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With