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

时间:2013-06-25 18:04:43

标签: 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;
}

这样做有效,但如果我将startdate更改为06/09/2013而将enddate更改为06/17/2013,则它应该可以正常工作。

如果startdate06/07/2013enddate06/15/2013,它甚至应该有效,但事实并非如此。有什么想法吗?

4 个答案:

答案 0 :(得分:26)

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

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

重叠测试稍微复杂一些。如果两个日期范围重叠,则无论顺序如何,以下内容都将返回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);

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

答案 1 :(得分:19)

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

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

相当于

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

答案 2 :(得分:12)

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

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

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

答案 3 :(得分:0)

这里是nodejs中的逻辑

    export const isDateOverlaped = (firstDateRange: { from: Date; to: Date }, secondDateRange: { from: Date; to: Date }) => {
  // f-from -----------f-to
  //          s-from -------------- s-to
  const overlappedEnd =
    firstDateRange.from <= secondDateRange.from && firstDateRange.to >= secondDateRange.from && firstDateRange.to <= secondDateRange.to

  // f-from ----------------------- f-to
  //          s-from --------- s-to
  const overlappedBetween = firstDateRange.from <= secondDateRange.from && firstDateRange.to >= secondDateRange.to

  //            f-from -----------f-to
  // s-from -------------- s-to
  const overlappedStart =
    firstDateRange.from >= secondDateRange.from && firstDateRange.from <= secondDateRange.to && firstDateRange.to >= secondDateRange.to

  return overlappedEnd || overlappedBetween || overlappedStart
}