moment获取当前周、根据周获取日期

2022-07-21  本文已影响0人  Xbbing

效果如下:

image.png
   需要先 npm i moment
   再import moment from 'moment'
  1. 获取当前年
  const curYear = new Date().getFullYear()

2.获取当前周

  const curWeek = moment().format("W")

3.获取当前周的开始日期和结束日期

  let weekOfDay = parseInt(moment().format('E'));//计算今天是这周第几天
  let last_monday = moment().startOf('day').subtract(weekOfDay - 1, 'days').toDate();//周一日期
  let last_sunday =  moment().startOf('day').subtract(weekOfDay - 7, 'days').toDate();//周日日期

4.获取某年某周的开始日期和结束日期

  const year = 2022
  const week = 29
  let  weekdays = []
  weekdays[0] = moment(`${year}-${week}`,'GGGG-WW').format('YYYY.MM.DD')
  weekdays[1] = moment(`${year}-${week}`,'GGGG-WW').weekday(7).format('YYYY.MM.DD')

5.上周下周日期变化

  // 日期格式获取
  const  getLastWeek = (i) => {
    let weekOfDay = parseInt(moment().format('E'));//计算今天是这周第几天
    let last_monday = moment().startOf('day').subtract(weekOfDay + 7 * i - 1, 'days').toDate();//周一日期
    let last_sunday =  moment().startOf('day').subtract(weekOfDay + 7 * (i - 1), 'days').toDate();//周日日期
    week = moment(last_monday).format('W') //获取此日期所在周
    year = moment(last_monday).format('Y')  //获得此日期所在年
    return [moment(last_monday).format('YYYY.MM.DD'), moment(last_sunday).format('YYYY.MM.DD')]
  }
  // 上周
  const beforeWeek = () => {
    weekCount++
    weekdays = getLastWeek(weekCount.value)
  }
  // 下周
  const nextWeek = () => {
    weekCount--
    weekdays = getLastWeek(weekCount.value)
  }
上一篇下一篇

猜你喜欢

热点阅读