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? Thanks
Solution 1:
const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD');
const numOfDays = firstDayOfMonth.daysInMonth();
let weeks = newSet();
for(let i = 0; i < numOfDays; i++){
const currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD').add(i, 'days');
weeks.add(currentDay.isoWeek());
}
returnArray.from(weeks)
Solution 2:
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;
Solution 3:
I know I should not, but I like this question :) can you improove this?
functionshowWeeks(year, month) {
let firstWeek = moment(newDate(year,month,1)).isoWeek();
let lastWeek = moment(newDate(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]
Post a Comment for "How To Get Week Numbers Of Current Month In Moment.js"