首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用moment找到与给定时间最接近的时间?

如何使用moment找到与给定时间最接近的时间?
EN

Stack Overflow用户
提问于 2019-04-12 10:31:30
回答 1查看 710关注 0票数 1

所以我有一个简单的代码,一个可以工作的代码,用moment得到离给定时间最近的时间。

代码语言:javascript
运行
复制
// 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);
代码语言:javascript
运行
复制
<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)。

我不知道我的帖子是否清楚,但请随时留下一些评论。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-04-12 11:05:49

去掉Math.abs,这样你就只有时间了。

代码语言:javascript
运行
复制
// 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);
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55643665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档