You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS/TS从时间槽数组中筛选出距离当前时间最近的两个时间段?

代码修正方案

原有代码问题

  • 仅通过字符串匹配判断,只能筛选到和当前时间完全一致的时间段,无法计算时间差找到最近的节点
  • 没有对时间做数值化处理,无法比较时间先后和间隔大小

修正思路

  1. 把所有HH:mm格式的时间统一转换为当日总分钟数的数字格式,方便计算差值
  2. 计算当前时间的当日总分钟数,需要固定IST时区可额外加时区配置
  3. 给每个预设时间段计算与当前时间的差值绝对值,按差值从小到大排序
  4. 取排序后的前两个时间段,就是距离最近的两个时间段

修正后代码

let timeArry = ["08:00", "08:15", "08:30", "08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00", "15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", "18:45", "19:00", "19:15", "19:30", "19:45", "20:00", "20:15", "20:30", "20:45", "21:00", "21:15", "21:30"];

// 转换时间为当日总分钟数的工具函数
const getMinute = (timeStr) => {
  const [hour, minute] = timeStr.split(':').map(Number)
  return hour * 60 + minute
}

// 固定使用IST时区获取当前时间,不需要时区限制可直接new Date()
const now = new Date(new Date().toLocaleString('en-US', { timeZone: 'Asia/Kolkata' }))
const currentMinute = now.getHours() * 60 + now.getMinutes()

// 按时间差排序取最近两个
const result = timeArry
  .map(time => ({
    time,
    diff: Math.abs(getMinute(time) - currentMinute)
  }))
  .sort((a, b) => a.diff - b.diff)
  .slice(0, 2)
  .map(item => item.time)

console.log(result)

按示例中的10:17测试,以上代码会返回['10:15', '10:30'],符合需求。

内容的提问来源于stack exchange,提问作者sandip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:24:03