2017-10-13 152 views
1

我有一個包含多個日期範圍的數組。我需要檢查一個日期是否在範圍內(檢查重疊日期現在不在範圍內)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

回答

0

在你的代碼,today是一個字符串,而dDate()。您將受益於更多描述性變量名稱,例如todayStringtodayDate

此外,我不確定「今日」是否具有描述性,因爲您在上做+1

如果您的datesArray是在JavaScript中確定的,那麼您可以在其中存儲Date()對象,但也許您是出於示例目的這麼做的。

0

@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"); 
} 
相關問題