我尝试了一种与这里看到的方法不同/更直观的方法。它可能比一些方法稍微长一点,但在我看来,它更清晰地说明了它在做什么。您可以在fiddle中检查代码是否有效。以下是代码:
var times = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM",
"03:00 AM", "07:00 AM", "06:00 PM"];
times.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
console.log(times);
var testTime = "05:00 PM";
function findNearestTime(times, currentTime) {
var allTimes = times.slice();
allTimes.push(currentTime);
allTimes.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
var indexOfCurrent = allTimes.indexOf(currentTime);
if (indexOfCurrent == 0) {
return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2 );
}else if (indexOfCurrent == allTimes.length - 1) {
return allTimes.slice(allTimes.length - 2, indexOfCurrent);
}else {
var currTime = new Date("01/01/2018 " + currentTime).getHours();
var currTimeLower = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent - 1,
indexOfCurrent)).getHours();
var currTimeUpper = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent + 1,
indexOfCurrent + 2)).getHours();
var leftDiff = currTime - currTimeLower;
var rightDiff = currTimeUpper - currTime;
if(leftDiff < rightDiff) {
return allTimes.slice(indexOfCurrent - 1, indexOfCurrent);
}
else {
return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2);
}
};
}
console.log(findNearestTime(times, testTime));
这里是可工作的示例。我测试了不同的时间,它可以正常运行。
https://jsfiddle.net/b36fxpqr/13/