JavaScript中判断指定hour、minute字符串是否距当前时间5分钟以内
实现思路
直接将目标时分和当前时间都转成时间戳计算间隔,不需要手动处理跨小时、跨天等边界场景,所有日期逻辑交给原生Date对象处理即可。
原代码问题说明
- 仅对比分钟维度的数值差,未纳入小时、日期维度的计算,遇到
14:00和13:57这类跨小时的场景会识别失败 - 未将数据库取出的字符串类型时间转为数字,直接做数值比较存在隐式类型转换的隐患
最终实现代码
// 从数据库获取的字符串类型触发时间 const targetHour = "14" const targetMinute = "55" const now = new Date() const FIVE_MINUTE_MS = 5 * 60 * 1000 // 转换为数值类型 const tHour = Number(targetHour) const tMin = Number(targetMinute) // 构造三个候选时间:前一天、当天、后一天的目标时分,覆盖跨天边界场景 const timeCandidates = [ new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, tHour, tMin), new Date(now.getFullYear(), now.getMonth(), now.getDate(), tHour, tMin), new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, tHour, tMin) ] // 计算最小时间差 const minDiff = Math.min(...timeCandidates.map(item => Math.abs(now.getTime() - item.getTime()))) // 间隔在5分钟以内则触发函数 if (minDiff <= FIVE_MINUTE_MS) { myFunc() }
如果不需要考虑跨天的触发场景(比如触发时间一定是当天的时分),可以简化为如下版本:
const targetHour = "14" const targetMinute = "55" const now = new Date() const FIVE_MINUTE_MS = 5 * 60 * 1000 const targetTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(targetHour), Number(targetMinute)) const diff = Math.abs(now.getTime() - targetTime.getTime()) if (diff <= FIVE_MINUTE_MS) { myFunc() }
内容的提问来源于stack exchange,提问作者gianlps
相关产品推荐
相关产品推荐

