简体   繁体   中英

Get all days of a week by week number using Moment.js

Given an ISO week number, how to get all the days in the week with Moment.js? If it's the start of the month and it's not Monday, the last few days from the previous month should also be returned.

Example: moment.daysOfISOWeek(28, 'DD') // returns [06 07 08 09 10 11 12]

You can approach this in a number of ways, one is to get the first week of the year, add the required number of weeks, then loop to get all the days of the required week.

Another is to build a string in the ISO year-week format and use moment to parse it to a date, eg for the 28th week of 2020 moment('2020W28') , then loop over the week as above.

The following demonstrates both methods.

 /* Return array of dates for nth ISO week of year ** @param {number|string} isoWeekNum - ISO week number, default is 1 ** @param {number|string} year - ISO week year, default is current year ** @returns {Array} of 7 dates for specified week */ function getISOWeekDates(isoWeekNum = 1, year = new Date().getFullYear()) { let d = moment().isoWeek(1).startOf('isoWeek').add(isoWeekNum - 1, 'weeks'); for (var dates=[], i=0; i < 7; i++) { dates.push(d.format('ddd DD MMM YYYY')); d.add(1, 'day'); } return dates; } // Documentation as above function getISOWeekDates2(isoWeekNum = 1, year = new Date().getFullYear()) { let d = moment(String(year).padStart(4, '0') + 'W' + String(isoWeekNum).padStart(2,'0')); for (var dates=[], i=0; i < 7; i++) { dates.push(d.format('ddd DD MMM YYYY')); d.add(1, 'day'); } return dates; } // Calculate start of week console.log(getISOWeekDates()) // Use ISO 8601 yearWweek format eg 2020W28 console.log(getISOWeekDates2()) console.log(getISOWeekDates2(28))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Supplying the year is important around the end and start of the year, eg 30 Dec 2019 is in the first week of 2020. Should the default be the calendar year, 2019, or the ISO week year, 2020?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM