检查一个日期是否在两个日期之间


78

我需要检查datea-dd/mm/yyyy格式的字符串-是否在其他两个具有相同格式的日期之间dd/mm/yyyy

我试过了,但是不起作用:

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";

var from = Date.parse(dateFrom);
var to   = Date.parse(dateTo);
var check = Date.parse(dateCheck );

if((check <= to && check >= from))      
    alert("date contained");

我使用了调试器并检查了tofrom变量是否有isNaN值。你可以帮帮我吗?


丹尼尔,您需要更新正确的答案。票数更多的答案不会只检查几个月的日期

Answers:


103

Date.parse支持mm/dd/yyyynot格式 dd/mm/yyyy。对于后者,请使用moment.js之类的库或执行如下所示的操作

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)

2
+1用于正确解析日期字符串,而不将其留给依赖于实现的解析器。
RobG

2
考虑数据库约定,首个日期应包含在内。例如check >= from && check < to
OnurYıldırım'16

@Diode check:02/23/2018 from:11/20/2018 to:12/31/2018它返回true。
chudasamachirag

2
@chudasamachirag:问题是关于解析dd / mm / yyyy格式。这些日期采用mm / dd / yyyy格式
二极管

47

与其直接比较日期,不如比较日期的getTime()值。getTime()函数以整数形式返回自1970年1月1日以来的毫秒数-确定一个整数是否落在其他两个整数之间应该是微不足道的。

就像是

if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime()))      alert("date contained");

NaNGetTime没有getTime方法也没有方法?
Bergi

2
当日期格式为-02/05/2013但日期为iso格式(date + time)如-2019-09-12T13:02:14.291Z时,它将完全正常工作,然后在比较日期之前使用 setHours方法,例如- let compareDate = new Date('checkDate').setHours(0, 0, 0, 0); let startDate = new Date('startDate').setHours(0, 0, 0, 0); let endDate = new Date('endDate').setHours(0, 0, 0, 0); console.log(compareDate <= endDate && compareDate >= startDate); 希望它能对其他人有所帮助:)
Sayan Samanta,

16

尝试以下内容。它将帮助您...

小提琴: http : //jsfiddle.net/RYh7U/146/

剧本:

if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
    alert("Availed");
else
    alert("Not Availed");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

有何不同?
Bergi 2013年

2
@Bergi:如果“日期”NAN为该函数,return False那么“Date you check Or Pass是”Not Availed或“In Valid这是我和他的代码之间的地狱区别”
Pandian

但是OP的if条件也可以吗?而问题是关于日期幸福 NaN摆在首位(它是不是在所有的浏览器)
BERGI

如果我想检查now下下降7:00am9:00pm
SI 8

dateCheck(“ 20/01/2015”,“ 22/01/2015”,“ 21/02/2015”)此案例无效
Bhavin Rana 2015年

9

拥有50票的答案仅在几个月内不会检查日期。这个答案是不正确的。下面的代码有效。

var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1);  // -1 because months are from 0 to 11
var to   = new Date(d2);
var check = new Date(c);

alert(check > from && check < to);

这是另一个答案中发布的代码,我更改了日期,这就是我注意到它不起作用的原因

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);


alert(check > from && check < to);

2

我创建了定制功能来验证给定的日期是否在两个日期之间。

var getvalidDate = function(d){ return new Date(d) }

function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
    return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}

1

基于已接受答案的简化方法。

以我为例,我需要检查当前日期(今天)是否在其他两个日期的范围内,因此使用newDate()而不是硬编码值,但是您可以清楚地知道如何使用硬编码日期。


var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to   = new Date('2020/01/31');
var check = new Date(currentDate);

console.log(check > from && check < to);


0

试试这个:

的HTML

<div id="eventCheck"></div>

JAVASCRIPT

// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

// Add Zero if it number is between 0-9
if(dd<10) {
    dd = '0'+dd;
}
if(mm<10) {
    mm = '0'+mm;
}

var today = yyyy + '' + mm + '' + dd ;


// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017

// Add Zero if it number is between 0-9
if(endDay<10) {
    endDay = '0'+endDay;
} 
if(endMonth<10) {
    endMonth = '0'+endMonth;
}

// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//



// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
    document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)';  // true
} else {
    document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}

小提琴:https : //jsfiddle.net/zm75cq2a/


0

这是用打字稿编写的Date Prototype方法:

Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
  if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
  return !minDate ? true : this.getTime() >= minDate.getTime()
    && !maxDate ? true : this.getTime() <= maxDate.getTime();
};

0

我做了与第一个答案@Diode相同的事情,但是我使用了一系列日期作为条件,我希望这个例子对某人有用

例如(与日期数组示例相同的代码)

var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]); 



var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];

dates.forEach(element => {
   let parts = element.split("/");
   let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
        if (date >= from && date < to) {
           console.log('dates in range', date);
        }
})


0

例如,假设您的日期即将到来,并且您需要安装momentjs以获取提前日期功能。

let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)

    let format = "MM/DD/YYYY";
    let startDate: any = moment().format(format);
    let endDate: any = moment().add(30, "days").format(format);
    let compareDate: any = moment(cmpDate).format(format);
    var startDate1 = startDate.split("/");
    var startDate2 = endDate.split("/");
    var compareDate1 = compareDate.split("/");

    var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
    var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
    var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);

    if (checkDate > fromDate && checkDate < toDate) {
      ... condition works between current date to next 30 days
    }

-1

试试这个

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(Date.now()))
        {
            alert('small');
        }else{
            alert('big');
        }

小提琴

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.