js获取月份每个周范围

列:2023-02


/**
 * 获取本月每个星期范围
 * @param {String} 例:2022-02
 */
export function allWeeks(now_month) {
  Date.prototype.format = function(fmt) {
    let o = {
      'M+': this.getMonth() + 1, //月份
      'd+': this.getDate(), //日
      'h+': this.getHours(), //小时
      'm+': this.getMinutes(), //分
      's+': this.getSeconds(), //秒
      'q+': Math.floor((this.getMonth() + 3) / 3), //季度
      'S': this.getMilliseconds() //毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  }

  let wArr = []
  let today = new Date(Date.parse(now_month))
  let year = today.getFullYear()
  let month = today.getMonth()
  let i = 0

  let start = new Date(year, month, 1) // 得到当月第一天
  let end = new Date(year, month + 1, 0) // 得到当月最后一天
  let end_day = end.getDay()
  let end_i = 0
  switch (end_day) {
    case 0:
      end_i = 0
      break
    case 1:
      end_i = 6
      break
    case 2:
      end_i = 5
      break
    case 3:
      end_i = 4
      break
    case 4:
      end_i = 3
      break
    case 5:
      end_i = 2
      break
    case 6:
      end_i = 1
      break
  }
  end = new Date(year, month + 1, end_i)
  let start_day = start.getDay() // 当月第一天是周几
  switch (start_day) {
    case 0:
      i = 0 + 1
      break
    case 1:
      i = 0
      break
    case 2:
      i = 0 - 1
      break
    case 3:
      i = 0 - 2
      break
    case 4:
      i = 0 - 3
      break
    case 5:
      i = 0 - 4
      break
    case 6:
      i = 0 - 5
      break
  }

  while (new Date(year, month, i + 6) <= end) {
    wArr.push(
      [
        new Date(year, month, i).format('yyyy-MM-dd'),
        new Date(year, month, i + 1).format('yyyy-MM-dd'),
        new Date(year, month, i + 2).format('yyyy-MM-dd'),
        new Date(year, month, i + 3).format('yyyy-MM-dd'),
        new Date(year, month, i + 4).format('yyyy-MM-dd'),
        new Date(year, month, i + 5).format('yyyy-MM-dd'),
        new Date(year, month, i + 6).format('yyyy-MM-dd')
      ]
    )
    i += 7
  };
  return wArr
}

嘉豪
29 声望0 粉丝