【问题标题】:Get all days of a week by week number using Moment.js使用 Moment.js 按周数获取一周中的所有天
【发布时间】:2020-07-29 18:07:17
【问题描述】:

给定一个 ISO 周数,如何使用 Moment.js 获取一周中的所有天数?如果是月初且不是星期一,则还应返回上个月的最后几天。

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

【问题讨论】:

  • 您可能会得到第一个 ISO 周的开始,然后添加 28 x 7 天以到达第 28 周的开始。循环 6 次,每次增加一天,以获得完整的一周。你试过什么?你会用哪一年?每年年初和年末的几天通常以上一年或下一年的周数计。

标签: javascript date momentjs


【解决方案1】:

您可以通过多种方式解决此问题,一种是获取一年中的第一周,添加所需的周数,然后循环获取所需一周的所有天数。

另一种方法是构建一个 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 e.g. 2020W28
console.log(getISOWeekDates2())
console.log(getISOWeekDates2(28))
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"&gt;&lt;/script&gt;

在年底和年初供应年份很重要,例如2019 年 12 月 30 日是 2020 年的第一周。默认应该是日历年 2019 年还是 ISO 周年 2020 年?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2021-07-21
    相关资源
    最近更新 更多