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

PHP如何生成支持自定义步长与起止时间的分段时间范围二维数组

时间区间数组生成实现
  • 可配置参数:起始时间、结束时间、时间间隔步长(单位:分钟)
  • 自动适配跨零点的时间场景
  • 输出格式与需求完全匹配

代码实现(JavaScript版本)

function generateTimeSlots(startTime, endTime, stepMinute) {
  // 时间字符串转总分钟数便于计算
  const timeToMin = (timeStr) => {
    const [h, m, s] = timeStr.split(':').map(Number)
    return h * 60 + m + s / 60
  }
  // 总分钟数转换为HH:MM:SS格式字符串
  const minToTime = (totalMin) => {
    const h = String(Math.floor(totalMin / 60) % 24).padStart(2, '0')
    const m = String(Math.floor(totalMin % 60)).padStart(2, '0')
    return `${h}:${m}:00`
  }

  const slots = []
  let currentStart = timeToMin(startTime)
  let endTotalMin = timeToMin(endTime)
  // 处理结束时间小于起始时间的跨天情况
  if (endTotalMin <= currentStart) endTotalMin += 24 * 60

  while (currentStart < endTotalMin) {
    const currentEnd = currentStart + stepMinute
    slots.push([minToTime(currentStart), minToTime(currentEnd)])
    currentStart = currentEnd
  }
  return slots
}

使用示例

// 生成7:30到次日00:00、间隔30分钟的时间区间数组
const result = generateTimeSlots('07:30:00', '00:00:00', 30)
console.log(result)

输出效果

[
  ["07:30:00", "08:00:00"],
  ["08:00:00", "08:30:00"],
  ["08:30:00", "09:00:00"],
  // ...中间区间省略
  ["23:30:00", "00:00:00"]
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:45:04