js判断当前时间是否在某个时间段内

话不多说,上代码

    // 判断时间范围
    const date = new Date()
    const seperator1 = "-"
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    let strDate = date.getDate()
    if (month >= 1 && month <= 9) {
        month = "0" + month
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate
    }
    const currentdate = year + seperator1 + month + seperator1 + strDate
    const beginDate='2019-01-21'
    const endDate='2019-01-31'
    const d1 = new Date(beginDate.replace(/\-/g, "\/"))
    const d2 = new Date(endDate.replace(/\-/g, "\/"))
    const dc = new Date(currentdate.replace(/\-/g, "\/"))
    if (beginDate != '' && endDate != '' && currentdate != ''  && dc >= d1 && dc <= d2) {
      console.log('在时间范围内')
    }
    else {
      console.log('不在时间范围内')
    }

 

你可能感兴趣的:(前端,js)