如何使用 Moment.js 从选定的 week/year 中获取一周的第一天和最后一天?

How to get first and last day of week from selected week/year using Moment.js?

我有一年和一周的数字 - YYYY[W] <-> 2022[9]。

我想转换使用 Moment.js 的那些,以便获得特定周的日期范围。

所以,类似于:

function(year, week){
   *convert into date range*
   return dateRange
}

//Assuming , week 9 of 2022 I should return something like ['28/02/2022','6/03/2022'] which correspond to first and last day of that week

目前正在查看文档,寻找解决方案:https://momentjs.com/docs/#/get-set/week-year/

欢迎就此主题提供任何帮助

假设第一天是星期一,这是您的解决方案:

function calculateDateFromWeekNumAndYear(year, week) {
  const firstDate = moment().day('Monday').year(year).week(week).format('YYYY-MM-DD');
  const lastDate = moment(firstDate).add(6, 'days').format('YYYY-MM-DD');
  const dateRange = [firstDate, lastDate];
  return dateRange;
}