0

Using a startDate and an endDate, i need to get an array of calendar weeks for each week between the dates. Example: startDate: 12/02/22 endDate: 01/28/23

Given these two dates, i need to get an array containing an entry for each calendar week. Expected result: ["48/2022", "49/22", "50/2022", "51/2022" .......... "04/2023"]

As i'm not very familiar with javascripts date objects, i'm not quite sure how to approach this problem. I'm open to pure javascript implementation but also to libraries like moment.js I have read through moment.js documentation but i don't think they have an out of the box feature for this.

1 Answers1

0

function weeks(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);

  var result = [];
  for (var i = start; i <= end; i.setDate(i.getDate() + 1)) {
    var year = i.getFullYear();
    var firstDayOfTheYear = new Date(year, 0, 1);
    var days = Math.floor((i - firstDayOfTheYear) / (24 * 60 * 60 * 1000));

    var week = Math.ceil((i.getDay() + 1 + days) / 7);

    var res = week + '/' + year;

    if (!result.includes(res)) result.push(res);
  }
  return result;
}

var result = weeks("2022-12-02", "2023-01-20");
console.log(result);
RobG
  • 142,382
  • 31
  • 172
  • 209
  • This doesn't seem to produce the desired results. For example, when using the dates in your example "2022-12-02", "2023-01-20", the result is following array: `['49/2022', '50/2022', '51/2022', '52/2022', '53/2022', '1/2023', '2/2023', '3/2023', '4/2023']` However, 2022 only has 52 Calendar weeks and the 2022-12-02 is in the 48th week. That being said, it gives me a basis to work with. Thanks for the help :) – femorom424 Dec 05 '22 at 21:05
  • The calculation of week number is wrong, this answer mixes local and UTC date values. See [*Get week of year in JavaScript like in PHP*](https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php). – RobG Dec 07 '22 at 04:15