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

I have a year and a week number - YYYY[W] <-> 2022[9].

I want to convert those using Moment.js in order to get the date range from that specific week.

  • The first day and the last day of that week is the best solution for my problem.
  • Or all the days from that specific week could also work.

So, something like :

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

Looking into the docs at the moment, looking for a solution : https://momentjs.com/docs/#/get-set/week-year/

Any help would be welcome on this topic



Solution 1:[1]

Assuming the first day is Monday, here is your solution:

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman