js计算当前周数及每周具体日期

js计算当前周数及每周具体日期,第1张

效果如图,选择年份,显示周数及对应日期

##写了一个函数,传入年份,返回周数数组
//设置周下拉框
export function setweekOption(year){//传入年份
    year=new Date(year).getFullYear()
    let days = getDay(year || new Date().getFullYear())
    let weeks = {};
    for (let i = 0; i < days.length; i++) {
      let weeksKeyLen = Object.keys(weeks).length;  
      let daySplit = days[i].split('_');
      if (weeks[weeksKeyLen] === undefined) {
        weeks[weeksKeyLen + 1] = [daySplit[0]]
      } else {
        if (daySplit[1] == '1') {
          weeks[weeksKeyLen + 1] = [daySplit[0]]
        } else {
          weeks[weeksKeyLen].push(daySplit[0])
        }
      }
    }
    let option= []
    let weeksKeyLen = Object.keys(weeks).length;
    for(let i = 1; i < weeksKeyLen+1; i++){
        let obj = {};
        obj.text = "第" + i + "周"+'('+weeks[i][0]+'-'+weeks[i][weeks[i].length-1]+')';
        obj.value = i;
        option.push(obj)

    }
    return option;
  }
  export function getDay(year) {
    let dates = [];
    for (let i = 1; i <= 12; i++) {
      for (let j = 1; j <= new Date(year, i, 0).getDate(); j++) {
        dates.push(formatNumber(i) + '/' + formatNumber(j) + '_' + new Date([year, formatNumber(i), formatNumber(j)].join('-')).getDay())//返回当年所有日期(带星期数)
      }
    }
    return dates;
  }
  export function  formatNumber(n) {
    return n.toString().length > 1 ? n : '0'+n
  }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1321538.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存