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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16080378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:12:18  来源:igfitidea点击:

Check if one date is between two dates

javascriptdate

提问by Daniel Garcia Sanchez

I need to check if a date- a string in dd/mm/yyyyformat - falls between two other dates having the same format dd/mm/yyyy

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

I tried this, but it doesn't work:

我试过这个,但它不起作用:

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");

I used debugger and checked, the toand fromvariables have isNaNvalue. Could you help me?

我使用调试器并检查,tofrom变量具有isNaN价值。你可以帮帮我吗?

回答by Diode

Date.parsesupports the format mm/dd/yyyynot dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

Date.parse支持的格式 mm/dd/yyyydd/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)

回答by Jasmine Howell

Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.

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

Something like

就像是

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

回答by Pandian

Try what's below. It will help you...

试试下面的内容。它会帮助你...

Fiddle :http://jsfiddle.net/RYh7U/146/

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

Script :

脚本 :

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

回答by Pandian

The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.

有 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);

This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work

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

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

回答by KARTHIKEYAN.A

I have created customize function to validate given date is between two dates or not.

我创建了自定义函数来验证给定的日期是否在两个日期之间。

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

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

回答by Andrew Mykhalchuk

Simplified way of doing this based on the accepted answer.

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

In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.

在我的情况下,我需要检查当前日期(今天)是否与其他两个日期的范围相同,因此使用 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);

回答by Doodl

Try this:

试试这个:

HTML

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
}

Fiddle: https://jsfiddle.net/zm75cq2a/

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

回答by Nate May

Here is a Date Prototype method written in typescript:

这是一个用打字稿编写的日期原型方法:

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

回答by Rafael Sequeira

I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone

我做了同样的事情@Diode,第一个答案,但我用一系列日期设置条件,我希望这个例子对某人有用

e.g (the same code to example with array of dates)

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

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

回答by Lal krishnan S L

Try this

试试这个

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

Fiddle

小提琴