我试图在数组或列表等中获得最近的时间。我能够找到此代码并尝试通过编辑使其工作,但没有任何运气。如果它更容易,可以使用jquery。下面只是 javascript 虽然我如何输出最接近时间 which = thetime 的时间
经过更多研究,我发现了这个片段,并认为它可能对我的事业有用:
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
我正在尝试什么
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
var thetime = hours + ":" + minutes + " "
var json = [{
"times": {
"times1": "20:01",
"times2": "21:43",
"times3": "22:56",
"times4": "23:21"
}
}]
var times = [];
var jsontimes = json[0].times;
for (var i in jsontimes) {
times.push(new Date(jsontimes[i]))
}
times.sort(function (a, b) {
return Math.abs(thetime - a / new Date()) + Math.abs(thetime - b / new Date())
});
// display code
for (var i = 0; i < jsontimes.length; i++)
document.getElementById("output").innerHTML += dates[i] + "<br>";