jQuery:检查日期是否在多个日期范围内

jQuery:检查日期是否在多个日期范围内

问题描述:

我有一个包含多个日期范围的数组。我需要检查一个日期是否在范围内(检查重叠日期现在不在范围内)jQuery:检查日期是否在多个日期范围内

到目前为止我有此代码,但即使今天的日期在其中一个,它也不会返回true日期范围。

// An array of objects containing date ranges 
var datesArray = [{ 
    "from": "2/12/2016", 
    "to": "8/12/2016", 
    "schedule": 1 
}, { 
    "from": "11/10/2017", 
    "to": "16/10/2017", 
    "schedule": 2 
}, { 
    "from": "17/10/2017", 
    "to": "22/10/2017", 
    "schedule": 3 
}]; 

// Today's date 
var d = new Date(); 
var dd = d.getDate(); 
var mm = d.getMonth() + 1; 
var yyyy = d.getFullYear(); 
var today = dd + "/" + mm + "/" + yyyy; 
console.log("Today: " + today); 

// For each calendar date, check if it is within a range. 
for (i = 0; i < datesArray.length; i++) { 
    // Get each from/to ranges 
    var From = datesArray[i].from.split("/"); 
    var To = datesArray[i].to.split("/"); 
    // Format them as dates : Year, Month (zero-based), Date 
    var FromDate = new Date(From[2], From[1] - 1, From[0]); 
    var ToDate = new Date(To[2], To[1] - 1, To[0]); 
    var schedule = datesArray[i].schedule; 

    // Set a flag to be used when found 
    var found = false; 
    // Compare date 
    if (today >= FromDate && today <= ToDate) { 
    found = true; 
    console.log("Found: " + schedule); 
    } 
} 

//At the end of the for loop, if the date wasn't found, return true. 
if (!found) { 
    console.log("Not found"); 
} 

JsFiddle here

我在这里错过了什么? 谢谢。

+0

'today'不是日期对象。 'd'是。试着比较一下? – rybo111

+0

^很好的一点。这里有很多问题。 – Taplar

+0

@ rybo111,这有助于解决我的问题。你能提供一个答案而不是评论吗? – Meek

在你的代码,today是一个字符串,而dDate()。您将受益于更多描述性变量名称,例如todayStringtodayDate

此外,我不确定“今日”是否具有描述性,因为您在上做+1

如果您的datesArray是在JavaScript中确定的,那么您可以在其中存储Date()对象,但也许您是出于示例目的这么做的。

@Taplar说什么,简单的解决办法:

var found = false 
// For each calendar date, check if it is within a range. 
for (i = 0; i < datesArray.length; i++) { 
..... 

    // Compare date 
    if (today >= FromDate && today <= ToDate) { 
    found = true; 
    console.log("Found: " + schedule); 
    break; //stop looping. 
    } 
} 

//At the end of the for loop, if the date wasn't found, return true. 
if (!found) { 
    console.log("Not found"); 
}