How to find the closest time to the given time using moment?

泪湿孤枕 提交于 2021-02-11 07:14:18

问题


So I have a simple code, a working code, that get's the nearest time to the given time using moment.

// Current time in millis
const now = +moment('10:16', 'HH:mm').format('x');
// List of times
const times = ["10:00", "10:18", "23:30", "12:00"];
// Times in milliseconds
const 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:18 but wanted to get 10:00
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

So what I wanted to do is to get the nearest time, before the given time but under the same minute? So in the example, the given time is 10:16 and in the array we have 10:00 and 10:18, so the output must be 10:00 since it's the nearest time before the given time with the same minute (10).

I don't know if my post is clear, but feel free to leave some comments. Thanks!


回答1:


Get rid of the Math.abs so you only get time before.

// Current time in millis
const now = +moment('10:16', 'HH:mm').format('x');
// List of times
const times = ["10:00", "10:18", "23:30", "12:00"];
// Times in milliseconds
const timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));

function closestTime(arr, time) {
  return arr.reduce(function(prev, curr) {
    return (curr - time) < (prev - time) ? curr : prev;
  });
}

const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');

// closest is 10:18 but wanted to get 10:00
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>


来源:https://stackoverflow.com/questions/55643665/how-to-find-the-closest-time-to-the-given-time-using-moment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!