Get all the dates from a given week number and year

Viewed 60

Suppose I have a week number 43 and a year 2020

How do I get so that the output would be

dates = ['Monday, October 19, 2020', 
        'Tuesday, October 20, 2020',
        'Wednesday, October 21, 2020',
        'Thursday, October 22, 2020',
        'Friday, October 23, 2020',
        'Saturday, October 24, 2020',
        'Sunday, October 24, 2020',]

I've tried this one but it gives me Sunday to Saturday which results to incorrect date range for week 43:

function getDateOfWeek(w, y) {
  var simple = new Date(y, 0, 1 + (w - 1) * 7);
  var dow = simple.getDay();
  var ISOweekStart = simple;
  if (dow <= 4)
    ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
  else
    ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
  const temp = {
    d: ISOweekStart.getDate(),
    m: ISOweekStart.getMonth(),
    y: ISOweekStart.getFullYear(),
  }
  const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()

  return Array.from({
    length: 7
  }, _ => {
    if (temp.d > numDaysInMonth) {
      temp.m += 1;
      temp.d = 1;
    }
    return new Date(temp.y, temp.m, temp.d++).toUTCString()
  });
}

console.log(getDateOfWeek(43, 2020));

1 Answers

As suggested by @Jamiec. All of the hassle by using native javascript date can be simplified by using momentjs

getDateOfWeek(d) {
            var startOfPeriod = this.moment(d),
            begin = this.moment(startOfPeriod).isoWeekday(1);

            begin.startOf('isoWeek');

            let str = '';
            for (var i = 0; i < 7; i++) {
                str += begin.format('ddd MMMM DD YYYY') + ',';
                begin.add('d', 1)
            }

            return str.split(',');
        },

above code will return the array of dates starting from monday to sunday

Related