[英]How to get week numbers of current month in moment.js
I want to get the week numbers of a particular month eg: January 2017 ,the weeknumbers in this months are [52,1,2,3,4,5] So how to get the above in an array? 我想获取特定月份的周数,例如:2017年1月,本月的周数为[52,1,2,3,4,5]那么如何在数组中获取以上数字? Thanks
谢谢
const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD');
const numOfDays = firstDayOfMonth.daysInMonth();
let weeks = new Set();
for(let i = 0; i < numOfDays; i++){
const currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD').add(i, 'days');
weeks.add(currentDay.isoWeek());
}
return Array.from(weeks)
So more efficiently: 这样更有效:
const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD');
let weekIndices = [];
let currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD');
weekIndices.push(currentDay.isoWeek());
while(currentDay.month() === firstDayOfMonth.month()) {
currentDay.add(1, 'weeks');
weekIndices.push(currentDay.isoWeek());
}
return weekIndices;
I know I should not, but I like this question :) can you improove this? 我知道我不应该,但是我喜欢这个问题:)您能改善吗?
function showWeeks(year, month) {
let firstWeek = moment(new Date(year,month,1)).isoWeek();
let lastWeek = moment(new Date(year,month+1,0)).isoWeek();
let out = [firstWeek];
if (firstWeek === 52 || firstWeek === 53) {
firstWeek=0;
}
for ( let i = firstWeek+1; i<= lastWeek; i++) {
out.push(i);
}
return out;
}
console.log(showWeeks(2017, 0)); // [52, 1, 2, 3, 4, 5]
console.log(showWeeks(2021, 0)); // [53, 1, 2, 3, 4]
console.log(showWeeks(2017, 11)); // [48, 49, 50, 51, 52]
console.log(showWeeks(1986, 9)); // [40, 41, 42, 43, 44]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.