Javascript/jquery-如何在数组中获得最接近的时间?

Javascript/jquery-如何在数组中获得最接近的时间?

问题描述:

我正在尝试获取数组或列表等中最近的时间。 我能够找到这段代码,并试图通过编辑来实现它,但没有任何运气。 如果它更容易,可以使用jquery。下面只是虽然 我怎么能输出最接近哪个= thetimeJavascript/jquery-如何在数组中获得最接近的时间?

进一步的研究之后的时间的时间,我发现这个片段,并认为这可能是我的事业有用的javascript:

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>"; 

您试图创建具有无效值(例如“20:01”)的Date对象,从而导致无效日期。根据MDN,你可以创建一个新的Date对象时通过以下方式传递参数:

Date(value) 
Date(dateString) 
Date(year, month, day [, hour, minute, second, millisecond]) 

其中 值是表示毫秒数从1970年1 00:00:00 UTC月份(的“整数值Unix Epoch)“。和

dateString是一个“表示日期的字符串值,该字符串应采用parse方法(IETF兼容的RFC 2822时间戳)识别的格式。”

你可以在这里阅读更多: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

这并没有真正回答你最初的问题,但它应该帮助你创建你想要的值的数组。