我希望能够设置不同的时间间隔

I want to be able to set different time intervals

我有这些代码可以帮助根据开始时间和结束时间生成一组时间, 它在 30 分钟或更短时间内运行良好,但在 1 小时 (60) 及以上时效果不佳...

export const getTimes = (start, end, timeInterval = 30) => {
  if (!start || !end) return
  start = parseInt(start) * 2 + (+start.slice(-2) > 0)
  end = parseInt(end) * 2 + (+end.slice(-2) > 0) + 1
  return Array.from({ length: end - start }, (_, i) => [
    (i + start) >> 1,
    ((i + start) % 2) * Number(timeInterval),
  ]).map(([h, m]) =>
    `${h % 12 || 12}:${m}${m.toString().length === 1 ? 0 : ""} ${
      "AP"[+(h > 11)]
    }M`.replace(/bdb/g, "0$&")
  )
}

console.log(getTimes("9:00", "22:00"))

结果是

["9:00 AM","9:30 AM","10:00 AM","10:30 AM","11:00 AM","11:30 AM","12:00 PM","12:30 PM","1:00 PM","1:30 PM","2:00 PM","2:30 PM","3:00 PM","3:30 PM","4:00 PM","4:30 PM","5:00 PM","5:30 PM","6:00 PM","6:30 PM","7:00 PM","7:30 PM","8:00 PM","8:30 PM","9:00 PM","9:30 PM","10:00 PM"]

但 1 小时(60)

["9:00 AM","9:60 AM","10:00 AM","10:60 AM","11:00 AM","11:60 AM","12:00 PM","12:60 PM","1:00 PM","1:60 PM","2:00 PM","2:60 PM","3:00 PM","3:60 PM","4:00 PM","4:60 PM","5:00 PM","5:60 PM","6:00 PM","6:60 PM","7:00 PM","7:60 PM","8:00 PM","8:60 PM","9:00 PM","9:60 PM","10:00 PM"]

你的间隔应该以分钟为单位。将分钟数添加到开始时间。将总分钟数转换为 HH:MM。 (注意我没有做 AM/PM,你可以算出来)

function getMins(time) {
  const parts = time.split(":");
  return +parts[0] * 60 + +parts[1];
}

function convertMins(totalMinutes) {
  const minutes = (totalMinutes % 60).toString().padStart(2, '0');
  let hrs = (totalMinutes-minutes)/60;
  const hours = hrs.toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}

function getTimes(start, end, timeInterval = 30) {
  const startMins = getMins(start);
  const endMins = getMins(end);
  return Array.from({ length: Math.ceil((endMins - startMins) / timeInterval) + 1 })
    .map((_, i) => convertMins( Math.min(startMins + i * timeInterval, endMins)));
}


console.log(getTimes("9:00", "22:00"))
console.log(getTimes("9:00", "22:00", 20))
console.log(getTimes("9:00", "22:00", 60))
console.log(getTimes("9:00", "22:00", 35))
console.log(getTimes("9:00", "22:00", 180))

谢谢大家,我终于搞定了

function generateTime(start, end, step) {
        const dt = new Date(`December 17, 1995 ${start}`);
        const dc = new Date(`December 17, 1995 ${end}`);
        const rc = [];
        while (dt <= dc) {
            rc.push(dt.toLocaleTimeString('en-US',{timeStyle: 'short'}));
            dt.setMinutes(dt.getMinutes() + step);
        }
        return rc;
    }
console.log(generateTime("9:00", "23:00", 90))