比较JavaScript中的两个特定日期

时间:2017-07-11 08:01:06

标签: javascript

我必须比较JS中的两个日期,代表下一个会话的开始。所有会话都保存在String数组中。如果actualSession结束,则nextSession将是实际的Session,而nextSession将成为数组的第一个元素,然后将其移出。但日期的比较并不奏效。你能救我吗?

function initializeComparison(){
getNextSession();
window.setInterval("getNextSession()", 15000);
}



function getNextSession(){
var actual_session = new Date(2017, 6, 22, 17,00);
var next_session = new Date(2017, 7, 6, 17, 00);
var allSessionsString = new Array("September 16, 2017 17:00:00", "September 
30, 2017 17:00:00"); //more to come, just for example

if(actual_session < next_session){
actual_session = next_session;
next_session = new Date(allSessionsString[0]);
allSessionsString.shift();

}

var element = document.getElementById("nextSession");
element.innerHTML = "Next Session: " + actual_session.toLocaleString();


}

2 个答案:

答案 0 :(得分:0)

问题是您在函数内声明了数组和变量。因此,每次通话都会重置,将其移到外面:

var actual_session = new Date(2017, 6, 22, 17,00);
var next_session = new Date(2017, 7, 6, 17, 00);
var allSessionsString =["September 16, 2017 17:00:00","September 30, 2017 17:00:00"]; 

 function getNextSession(){...}

答案 1 :(得分:0)

由于getNextSession方法中的变量的本地声明,因此不保留值

  • HTML 下届会议

-js

function initializeComparison(){
 actual_session = new Date(2017, 6, 22, 17,00);
 next_session = new Date(2017, 7, 6, 17, 00);
 allSessionsString = new Array("September 16, 2017 17:00:00", "September 30, 2017 17:00:00"); //more to come, just for example
 refreshIntervalId = window.setInterval("getNextSession()", 5);
}



function getNextSession(){

if(actual_session < next_session){
actual_session = next_session;
next_session = new Date(allSessionsString[0]);
if(typeof allSessionsString[0] == "undefined"){clearInterval(refreshIntervalId);}
allSessionsString.shift();
}
var element = document.getElementById("nextSession");
element.append ("Next Session: " + actual_session.toLocaleString());
}

工作小提琴https://jsfiddle.net/sainadhvemula/rmw36r90/6/