我正在尝试进行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)
这工作,但如果我改startdate
到06/09/2013
和enddate
到06/17/2013
它不再起作用,而它应该工作.
它甚至应该工作,如果startdate
是06/07/2013
和enddate
是06/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的答案可能更优雅,因为它只检查两个日期范围的开始/结束对.
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)
归档时间: |
|
查看次数: |
44587 次 |
最近记录: |