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

如何用JavaScript生成指定起止时间内半小时间隔的时间对字符串数组

解决方案:生成半小时间隔的时间对数组

没问题,我来帮你调整这段代码,让它输出你想要的半小时间隔时间对格式~

你原来的代码逻辑是生成每个半小时节点的单个时间字符串,但我们需要的是相邻两个时间节点组成的区间(比如13:00-13:30),所以核心改动是把每个时间点和它的下一个半小时点拼接成区间。

修改后的代码

function getTimeIntervals(start, end) {
  // 将时间字符串转换为"半小时刻度数":13:00 →26,13:30→27,以此类推
  const convertToTick = (timeStr) => {
    const [hour, minute] = timeStr.split(':').map(Number);
    return hour * 2 + (minute >= 30 ? 1 : 0);
  };

  const startTick = convertToTick(start);
  const endTick = convertToTick(end);

  // 生成每个时间区间
  return Array.from({ length: endTick - startTick }, (_, index) => {
    const currentTick = startTick + index;
    const nextTick = currentTick + 1;

    // 将刻度数转换回标准时间字符串(保证两位小时)
    const formatTickToTime = (tick) => {
      const hour = Math.floor(tick / 2);
      const minute = tick % 2 === 0 ? '00' : '30';
      return `${hour.toString().padStart(2, '0')}:${minute}`;
    };

    return `${formatTickToTime(currentTick)}-${formatTickToTime(nextTick)}`;
  });
}

// 测试示例:从13:00到23:00
console.log(getTimeIntervals("13:00", "23:00"));

代码说明

  1. 刻度转换逻辑:convertToTick函数把时间字符串转换成以半小时为单位的刻度数,这样我们可以用整数来计算间隔,避免处理时间的复杂计算。
  2. 区间生成:通过endTick - startTick确定要生成的区间数量,每个区间对应currentTick到nextTick的时间范围。
  3. 时间格式化:formatTickToTime函数把刻度数转回标准时间字符串,用padStart(2, '0')确保小时数是两位(比如9点会变成09:00)。

测试输出

运行上述代码后,你会得到符合需求的数组:

['13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00', ..., '22:30-23:00']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:22:30