JS判断当前时间是否在某个时间区间内
运行JS代码,很多时候需要通过时间判断事件是否执行。
下面一段代码,可以通过小时及分钟区间,判断是否运行事件
function checkAuditTime(beginTime, endTime) { var nowDate = new Date(); var beginDate = new Date(nowDate); var endDate = new Date(nowDate); var beginIndex = beginTime.lastIndexOf("\:"); var beginHour = beginTime.substring(0, beginIndex); var beginMinue = beginTime.substring(beginIndex + 1, beginTime.length); beginDate.setHours(beginHour, beginMinue, 0, 0); var endIndex = endTime.lastIndexOf("\:"); var endHour = endTime.substring(0, endIndex); var endMinue = endTime.substring(endIndex + 1, endTime.length); endDate.setHours(endHour, endMinue, 0, 0); return nowDate.getTime() - beginDate.getTime() >= 0 && nowDate.getTime() <= endDate.getTime(); } if (checkAuditTime("8:00", "11:00") || checkAuditTime("13:00", "17:00")) { alert("休息吃饭时间"); } else { alert("娱乐"); }