js获取当前日期是第几周、每年有多少周、周的开始时间和结束时间
2022-03-01 本文已影响0人
李仁平
这里以moment.js作编写。
视图:
image.png
代码:
//引入moment.js
import moment from 'moment';
//获取一年中有多少周、每一周开始和结束时间
const mapWeeksOfyear = ({ year} = {}) => {
const nowYear = year ? year : moment().year();
const timestamp = (new Date()).valueOf()
// 设置正在处理的年份
let handleYear = moment(new Date(String(nowYear)));
// 这一年有多少个周
const totalWeeks = handleYear.endOf('year').isoWeek();
const arryWeek = [];
let currentWeek = null; //当前日期是第几周
for(let i = 1;i <= totalWeeks;i++){
let startOf = handleYear.week(i).startOf('week').format('MM-DD');
let endOf = handleYear.week(i).endOf('week').format('MM-DD');
let ednyear = handleYear.week(i).endOf('week').format('YYYY');
let startValue= handleYear.week(i).startOf('week').valueOf();
let endValue= handleYear.week(i).endOf('week').valueOf();
if(startValue<=timestamp&&endValue>=timestamp){
currentWeek = i
}
arryWeek.push({
value: i,
name: `第${i}周 ${ednyear>nowYear?nowYear + "-" +startOf :startOf} 至 ${ednyear>nowYear?ednyear + "-" +endOf:endOf}`,
startTime: handleYear.week(i).startOf('week').format('YYYY-MM-DD'),// 这周的开始时间
endTime: handleYear.week(i).endOf('week').format('YYYY-MM-DD'), // 这周的结束时间
})
}
return {arryWeek,currentWeek}
}
关注小编不定时更新更多精彩内容。