2017-10-04 16 views
0

我有Schedule數組,其中包含開始/結束日期時間及其佈局名稱。從數組中搜索的JavaScript日期時間

let schedule=[ 
    { 
    "start": "2017-10-01 08:00:00", 
    "end": "2017-10-01 09:00:00", 
    "layout": "layout1.json" 
    }, 
    { 
    "start": "2017-10-01 10:00:00", 
    "end": "2017-10-01 12:00:00", 
    "layout": "layout2.json" 
    }, 
] 

let current_time = "2017-10-01 10:30:00"; 

如果當前日期時間是需要得到的佈局名稱layout2.json**current_time**。 需要使用JavaScript在上面的數組中搜索dateTime。

我嘗試下面的代碼,但它不工作..

for (i = 0; i < schedule.length; i++){ 
    if (schedule[i].start >= current_time && schedule[i].end <= current_time){ 
    return schedule[i].layout; 
    } 
} 

幫我,謝謝

+0

的可能的複製[比較兩個日期的JavaScript(https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Amit

+0

你是比較時間爲字符串,而不是日期對象。請務必將時間值設爲新日期(「2017-10-01 10:30:00」) – IonicBurger

+0

您試圖將字符串與日期時間進行比較 – Vamsi

回答

1

你需要在比較之前的日期轉換爲JS日期。

for (i = 0; i < schedule.length; i++){ 
    if (new Date(schedule[i].start)<= new Date(current_time) && new Date(schedule[i].end) >= new Date(current_time)){ 
     return schedule[i].layout; 
    } 
} 
+0

其不工作https://jsfiddle.net/8aguoefp/1/請檢查它在小提琴 – bijus

+0

你有反向的comperators,在我的答案糾正它,並更新jsfiddle:https://jsfiddle.net/zmb73598/ – Nayish

+0

感謝它的工作 – bijus