js判断2个时间段是否有重叠(时分)

原理:1天1440分钟,每个时间段都有对应的数值,生成2个数组,判断数组中是否有重叠数字

isTimeOverlap(startA, endA, startB, endB) {
      if (!startA || !endA || !startB || !endB) return false
      let sA = this.dealTime(startA);
          let sB = this.dealTime(startB);
          let eA = this.dealTime(endA);
          let eB = this.dealTime(endB)
      //不是时间段
      if (sA === eA || sB === eB) return true

      let isOverlap = false

      let arrA = [] // 第一个时间段的区间
      if (sA < eA) {
        for (let i = sA; i < eA; i++) {
          arrA.push(i)
        }
      } else {
        for (let i = sA; i < 1440; i++) {
          arrA.push(i)
        }
        for (let i = 0; i < eA; i++) {
          arrA.push(i)
        }
      }
      let arrB = [] // 第2个时间段的区间
      if (sB < eB) {
        for (let i = sB; i < eB; i++) {
          arrB.push(i)
        }
      } else {
        for (let i = sB; i < 1440; i++) {
          arrB.push(i)
        }
        for (let i = 0; i < eB; i++) {
          arrB.push(i)
        }
      }
      for (let i = 0; i < arrA.length; i++) {
        let h = arrB.findIndex((item) => { return item === arrA[i] })
        if (h !== -1)isOverlap = true
      }

     //console.log(sA, sB, eA, eB, JSON.stringify(arrA),'\n', JSON.stringify(arrB))
      return isOverlap;
    },
    dealTime(time) {
      let t = time.split(":")
      return parseInt(t[0]) * 60 + parseInt(t[1])
    },

  调用:

      this.dataForm.dayModeTime1 = '14:00'
      this.dataForm.dayModeTime2 = '22:00'

      this.dataForm.nightModeTime1 = '22:00'
      this.dataForm.nightModeTime2 = '12:00'

     this.isTimeOverlap(this.dataForm.dayModeTime1, this.dataForm.dayModeTime2, this.dataForm.nightModeTime1, this.dataForm.nightModeTime2)

    

  

posted @ 2024-01-10 14:26  庞某人  阅读(361)  评论(0编辑  收藏  举报