JavaScript日期范围介于日期范围之间

jfr*_*k53 14 javascript date

我正在尝试进行IF检查以查看X日期范围是否在Y日期范围之间.但它没有在正确的时间返回正确的真/假:

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;
}
Run Code Online (Sandbox Code Playgroud)

这工作,但如果我改startdate06/09/2013enddate06/17/2013它不再起作用,而它应该工作.

它甚至应该工作,如果startdate06/07/2013enddate06/15/2013,但其实不然.有什么想法吗?

voi*_*hos 28

如果您正在尝试检测完全遏制,那就相当容易了.(另外,你不需要显式return true/false,因为条件是一个布尔值.只需返回它)

// Illustration:
//
// startdate                          enddate
// v                                        v
// #----------------------------------------#
//
//         #----------------------#
//         ^                      ^
//         startD              endD
return startD >= startdate && endD <= enddate;
Run Code Online (Sandbox Code Playgroud)

重叠测试稍微复杂一些.true如果两个日期范围重叠,则无论顺序如何,都将返回以下内容.

// 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);
Run Code Online (Sandbox Code Playgroud)

@ Bergi的答案可能更优雅,因为它只检查两个日期范围的开始/结束对.

  • 提示:使用`startD.getTime()`而不仅仅是日期对象进行比较,因为使用日期对象将首先转换为字符串并比较为字符串,因为getTime()比较的整数值快10倍以上(在FF中,20x在Chrome中) - 当然不重要,除非需要比较很多日期.非科学测试:http://jsperf.com/test-time-vs-gettime (3认同)

Ber*_*rgi 20

要检查它们是否与任何日期重叠,请使用

if (endD >= startdate && startD <= enddate)
Run Code Online (Sandbox Code Playgroud)

这相当于

if ( !(endD < startdate || startD > enddate)) // not one after the other
Run Code Online (Sandbox Code Playgroud)


Bun*_*gus 12

在您的示例中,新日期都在范围之外.

如果要检查日期范围之间是否有任何重叠,请使用:

return (endD >= startdate && startD <= enddate);
Run Code Online (Sandbox Code Playgroud)