问题
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