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

如何在JavaScript中比较两个时间并根据当前时间判断正在进行的课程

原代码问题点

  • 对带冒号、AM/PM标识的时间字符串直接调用parseInt(),只会提取第一个冒号前的数字,无法得到可用于比较的有效时间数值
  • 区间判断逻辑错误:判断当前时间是否落在起止时间区间内需要使用&&逻辑与,原代码用||逻辑或会导致大部分场景都错误命中判定

修复方案

最优实现思路是将所有时间统一转换为当日累计分钟数(取值范围0~1440),直接比较数字即可避免时间格式转换的问题,修复后代码如下:

// 获取当前时间的当日累计分钟数
const now = new Date()
const currentTotalMin = now.getHours() * 60 + now.getMinutes()

// 转换"HH:MM:AM/PM"格式字符串为当日累计分钟数
function convertTimeToMin(timeStr) {
  const [hourStr, minStr, period] = timeStr.split(':')
  let hour = parseInt(hourStr, 10)
  const min = parseInt(minStr, 10)
  if (period === 'PM' && hour !== 12) hour += 12
  if (period === 'AM' && hour === 12) hour = 0
  return hour * 60 + min
}

const start_time = "09:00:PM"
const end_time = "10:00:PM"
const startMin = convertTimeToMin(start_time)
const endMin = convertTimeToMin(end_time)

if (currentTotalMin >= startMin && currentTotalMin <= endMin) {
  console.log("C programming class is going")
} else {
  console.log("No class are available")
}

如果需要同时判断多门课程,只需要把所有课程的起止时间、课程名存入数组,循环遍历判断即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 07:15:07