簡體   English   中英

使用 Moment.js 按周數獲取一周中的所有天數

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

給定一個 ISO 周數,如何使用 Moment.js 獲取一周中的所有天數? 如果是月初且不是星期一,則還應返回上個月的最后幾天。

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

您可以通過多種方式解決此問題,一種是獲取一年中的第一周,添加所需的周數,然后循環獲取所需周的所有天數。

另一種是構建一個 ISO 年-周格式的字符串,並使用 moment 將其解析為日期,例如 2020 年第 28 周moment('2020W28') ,然后像上面那樣循環一周。

下面演示了這兩種方法。

 /* 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>

在年末和年初提供年份很重要,例如 2019 年 12 月 30 日是 2020 年的第一周。默認值應該是日歷年 2019 年還是 ISO 周年 2020 年?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM