我想找到距离给定时间最近的下一个时间,我从堆栈溢出中得到了这段代码,但我无法获得所需的结果// Current time in millisconst now = +moment('10:07', 'HH:mm').format('x');// List of timesconst times = ["10:00", "10:18", "23:30", "12:00"];// Times in millisecondsconst timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));function closestTime(arr, time) { return arr.reduce(function(prev, curr) { return Math.abs(curr - time) < Math.abs(prev - time) ? curr : prev; });}const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');// closest is 10:00 but i want the next time 10:18console.log(closest);<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
1 回答
喵喔喔
TA贡献1735条经验 获得超5个赞
根本不需要片刻
24小时时间可排序,可直接比较
const times = ["10:00", "10:18", "23:30", "12:00"].sort();
const getClosest = targetTime => times.find(time => time >= targetTime) || "N/A";
console.log(getClosest("10:07"));
console.log(getClosest("11:30"));
console.log(getClosest("13:30"));
console.log(getClosest("23:40")); // not available in array
添加回答
举报
0/150
提交
取消