JavaScript判断当前时间是否早于指定时间(8:20AM)失败求助
问题排查与修复
原代码的问题
- 单位不统一:左边
+now / _MS_IN_MIN得到的是从1970年至今的总分钟数,而右边8 * _MS_IN_HOUR + 20 * _MS_IN_MIN是8小时20分对应的毫秒数,两者单位和含义完全不同,无法正确比较。 - 逻辑偏差:代码意图是判断当天当前时间是否早于8:20,但原代码没有针对“当天”做处理,而是拿累计时间量做对比,逻辑完全错误。
正确实现方式
方法1:直接提取当前小时和分钟对比
最直观的方式,获取当前时间的小时和分钟,直接和目标时间的时分比较:
const now = new Date(); const currentHour = now.getHours(); const currentMinute = now.getMinutes(); // 判断是否早于8:20 if (currentHour < 8 || (currentHour === 8 && currentMinute <= 20)) { console.log("something"); }
方法2:转换为当天的总分钟数对比
把当前时间和目标时间都转成当天的总分钟数(0点到当前的分钟数),再做比较:
const now = new Date(); // 当天总分钟数:小时*60 + 分钟 const currentTotalMinutes = now.getHours() * 60 + now.getMinutes(); // 目标时间的总分钟数:8*60+20=500 const targetTotalMinutes = 8 * 60 + 20; if (currentTotalMinutes <= targetTotalMinutes) { console.log("something"); }
方法3:创建当天的目标时间对象对比
生成当天8:20的Date实例,直接和当前时间对比:
const now = new Date(); // 创建当天8:20的Date对象 const targetTime = new Date( now.getFullYear(), now.getMonth(), now.getDate(), 8, 20, 0, 0 ); if (now <= targetTime) { console.log("something"); }
内容的提问来源于stack exchange,提问作者Viroz
相关产品推荐
相关产品推荐

