简体   繁体   English

使用 Moment.js 按周数获取一周中的所有天数

[英]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?给定一个 ISO 周数,如何使用 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]示例: 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.另一种是构建一个 ISO 年-周格式的字符串,并使用 moment 将其解析为日期,例如 2020 年第 28 周moment('2020W28') ,然后像上面那样循环一周。

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?在年末和年初提供年份很重要,例如 2019 年 12 月 30 日是 2020 年的第一周。默认值应该是日历年 2019 年还是 ISO 周年 2020 年?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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