js 获取今天/昨天/本周/上周/本月/上月/本季度/上季度/今年的时间

getTime(val) {
      let datenow = new Date()
      let nowDay = datenow.getDate() //当前日
      let nowMonth = datenow.getMonth() //当前月
      let nowYear = datenow.getFullYear() //当前年
      let nowDayOfWeek = datenow.getDay() //今天本周的第几天
      let jd = Math.ceil((nowMonth + 1) / 3)
      let startTime = ''
      let endTime = ''
      if (val == '今天') {
        //今天
        startTime = new Date(nowYear, nowMonth, nowDay)
        endTime = new Date(
          nowYear,
          nowMonth,
          nowDay,
          23,
          59
        )
      } else if (val == '昨天') {
        //昨天
        startTime = new Date(
          nowYear,
          nowMonth,
          nowDay - 1
        )
        endTime = new Date(
          nowYear,
          nowMonth,
          nowDay - 1,
          23,
          59
        )
      } else if (val == '本周') {
        //本周
        startTime = new Date(
          nowYear,
          nowMonth,
          nowDay - nowDayOfWeek + 1
        )
        endTime = new Date(
          nowYear,
          nowMonth,
          nowDay + (7 - nowDayOfWeek)
        )
      } else if (val == '上周') {
        //上周
        let day = datenow.getDay() == 0 ? 7 : datenow.getDay()
        startTime = new Date(
          nowYear,
          nowMonth,
          nowDay - 6 - day
        )
        endTime = new Date(
          nowYear,
          nowMonth,
          nowDay - day
        )
      } else if (val == '本月') {
        //本月
        startTime = new Date(nowYear, nowMonth, 1)
        endTime = new Date(nowYear, nowMonth + 1, 0)
      } else if (val == '上月') {
        //上月
        startTime = new Date(nowYear, nowMonth - 1, 1)
        endTime = new Date(
          nowYear,
          nowMonth,
          nowDay - nowDay
        )
      } else if (val == '本季度') {
        //本季度
        startTime = new Date(nowYear, (jd - 1) * 3, 1)
        endTime = new Date(nowYear, jd * 3, 0)
      } else if (val == '上季度') {
        //上季度
        startTime = new Date(
          nowYear,
          (jd - 1) * 3 - 3,
          1
        )
        endTime = new Date(nowYear, jd * 3 - 3, 0)
      } else if (val == '今年') {
        //今年
        startTime = new Date(nowYear, 0, 1)
        endTime = new Date(nowYear, 11, 31)
      }
      return {
        startTime,
        endTime
      }
    }

你可能感兴趣的:(js 获取今天/昨天/本周/上周/本月/上月/本季度/上季度/今年的时间)