Welcome

首页 / 脚本样式 / JavaScript / 判断时间段是否有效,即判断当前时间是否在指定的时间范围内

判断时间段是否有效,即判断当前时间是否在指定的时间范围内

function checkTimeValid(startTime, endTime){
    // 获取当前时间
    const date  = new Date()
    // 获取当前时间的年月日
    const dataStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} `
    // 获取开始时间、结束时间、现在时间的时间戳
    let startDate = new Date(dataStr + startTime).getTime()
    let endDate = new Date(dataStr + endTime).getTime()
    let nowDate = date.getTime()
    const s = startDate > endDate // 判断开始时间否大于结束时间
    if(s) [startDate, endDate] = [endDate, startDate] // 若开始时间否大于结束时间则交换值
    // 判断现在的时间是否在开始时间和结束时间之间,若s为true则结果取反
    if(nowDate > startDate && nowDate < endDate){
        return s ? false : true
    }else{
        return s ? true : false
    }
}

使用方法:

var flag=checkTimeValid('10:00:00','23:15:15');
if(flag){
    //在指定的时间范围内
}else{
    //不在指定时间范围内
}