根据当前月份取当前月份多少周及起始日期

146 阅读1分钟

根据当前指定月份,获取该月份每周的起始日期:

<body>
<input placeholder="请输入" id="time" value="2023-10-01">
<button onclick="computingTime()">计算</button>
<div id="demo"></div>
</body>
<script>
  computingTime = () => {
    const v = document.getElementById('time').value
    let obj = {
      1: '一',
      2: '二',
      3: '三',
      4: '四',
      5: '五',
      6: '六'
    }
    const time = new Date(v)
    const year = time.getFullYear()
    const month = time.getMonth() + 1

    // 获取当月的第一天
    const firstDay = new Date(year, month - 1, 1)
    // 获取当月的最后一天
    const lastDay = new Date(year, month, 0)
    const days = lastDay.getDate() // 多少天
    const firstDayOfWeek = firstDay.getDay()
    const lastDayWeek = lastDay.getDay()
    // 第一天是周日
    const weeks = firstDayOfWeek === 0 || lastDayWeek === 1 ? Math.ceil((days) / 7) + 1 : Math.ceil((days + firstDayOfWeek) / 7)

    let dates = []
    for (let i = 0; i < weeks; i++) {
      let start,end
      if (firstDayOfWeek === 0) {
        start = i === 0 ? (i * 7 + 1) : (i * 7 - 5)
        end = Math.min(i === 0 ? start : start + 6, days)
      } else {
        start = i * 7 - firstDayOfWeek + 2
        end = Math.min(start + 6, days)
      }
      dates.push({
        name: '第' + obj[i + 1] + '周',
        index: i,
        start: start > 0 ? start : 1,
        end: end,
        time: [start > 0 ? start : 1, end].join('~').replace(/(?=\b\d\b)/g, '0')
      })
    }
    document.getElementById('demo').innerHTML = JSON.stringify(dates)
  }

</script>