本文介绍了JavaScript日期范围在日期范围之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图进行IF检查,以查看X日期范围是否在Y日期范围之间。但是在正确的时间没有返回正确的/ false:

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;
}

这是有效的,但如果我更改 startdate 06/09/2013 enddate 06/17 /如果 startdate

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.

它应该甚至可以工作> 06/07/2013 enddate 06/15/2013 ,但没有。任何想法?

It should even work if startdate was 06/07/2013 and enddate was 06/15/2013, but doesn't. Any thoughts?

推荐答案

如果您想要检测到完整的遏制,那是相当容易的。 (另外,您不需要显式的 return true / false ,因为条件是布尔值,只要返回)

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;






重叠测试稍微复杂一点。如果两个日期范围重叠,则无论订单如何,以下内容将返回 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的答案可能更为优雅,因为它只是检查两个开始/结束对日期范围。

@Bergi's answer is probably more elegant, in that it just checks the start/end pairs of the two date ranges.

这篇关于JavaScript日期范围在日期范围之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 17:46