如何使用moment找到最接近给定时间的时间? [英] How to find the closest time to the given time using moment?
问题描述
所以我有一个简单的代码,一个工作代码,它使用 moment 获取到给定时间的最近时间.
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>
所以我想要做的是在给定时间之前但在同一分钟内获得最近的时间?所以在这个例子中,给定的时间是 10:16,在数组中我们有 10:00 和 10:18,所以输出必须是 10:00,因为它是给定时间之前最接近的时间,具有相同的分钟 (10).
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!
推荐答案
摆脱 Math.abs 这样你就只剩下时间了.
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>
这篇关于如何使用moment找到最接近给定时间的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!