Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript date range between date range

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?

like image 255
jfreak53 Avatar asked Jun 25 '13 18:06

jfreak53


3 Answers

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.

like image 88
voithos Avatar answered Oct 09 '22 01:10

voithos


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
like image 20
Bergi Avatar answered Oct 09 '22 00:10

Bergi


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);
like image 28
Bungus Avatar answered Oct 08 '22 23:10

Bungus