0

I have the following code to get the week number when I rpovide a date

Date.prototype.getWeek = function () {
        var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
        d.setUTCDate(d.getUTCDate() - d.getUTCDay());
        var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
        return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    }

when I pass the date 2018-01-01 the weekNumber is given as 53 as january 1st of 2018 lay on the last week of 2017. How can I get the week number by making the year start at january 1st instead of making the the start day of each week is a sunday ?

charlietfl
  • 170,828
  • 13
  • 121
  • 150
tharindu
  • 513
  • 6
  • 26

1 Answers1

0

You can calculate the number of whole weeks since Jan 1 using UTC date values to avoid daylight saving issues. Starting from 1ms before 1 Jan and using Math.ceil means 1 Jan is the first day of week 1.

The following is a slight refactoring of your code:

// Get week number based on start of 1 Jan
function getWeekNumber(date = new Date()) {
  const msPerWeek = 5.828e8;
  // Use UTC values to remove timezone issues
  let d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  // Set epoch to 1 ms before 1 Jan
  let e = new Date(Date.UTC(d.getUTCFullYear(), 0, 0, 23, 59, 59, 999));
  // Return week number
  return Math.ceil((d - e) / msPerWeek);
}

[new Date(2019,0,1),  // Tue 1 Jan, week 1
 new Date(2019,0,7),  // Mon 7 Jan, week 1
 new Date(2019,0,8),  // Tue 8 Jan, week 2
 new Date(2019,0,15), // Tue 15 Jan, week 3
 new Date()           // Today
].forEach( date => console.log(date.toDateString() + ': ' + getWeekNumber(date)));
RobG
  • 142,382
  • 31
  • 172
  • 209