0

I am using a function to get the weekNumber within my app, returning an integer as a result, which works as intended, the code is:

Date.prototype.getWeek = function(dowOffset) {

  dowOffset = Number.isInteger(dowOffset)? dowOffset : 0; //default dowOffset to zero
  var newYear = new Date(this.getFullYear(), 0, 1);
  var day = newYear.getDay() - dowOffset; //the day of week the year begins on
  day = (day >= 0 ? day : day + 7);
  var daynum = Math.floor((this.getTime() - newYear.getTime() -
    (this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) / 86400000) + 1;
  var weeknum;
  //if the year starts before the middle of a week
  if (day < 4) {
    weeknum = Math.floor((daynum + day - 1) / 7) + 1;
    if (weeknum > 52) {
      nYear = new Date(this.getFullYear() + 1, 0, 1);
      nday = nYear.getDay() - dowOffset;
      nday = nday >= 0 ? nday : nday + 7;
      /*if the next year starts before the middle of
        the week, it is week #1 of that year*/
      weeknum = nday < 4 ? 1 : 53;
    }
  } else {
    weeknum = Math.floor((daynum + day - 1) / 7);
  }
  return weeknum;
};

for (var d, i=10; i; i--) {
  d = new Date(2029 - i, 11, 31);
  console.log(d.toString() +  ' which is week ' + d.getWeek(1));
}

(Answer taken from JavaScript Date.getWeek()

This all works as intended, yet if the final days of the year (say December 30th & December 31st), fall into the first week of the year, it does not read them within week 1, instead, errors returning no result?

How would I alter this code to ensure that the result will return the first week number when the days could possibly be within the final month of the year?

RobG
  • 142,382
  • 31
  • 172
  • 209
Ldweller
  • 327
  • 2
  • 16
  • 3
    After fixing the erroneous *typeof* test, testing for 31 December for 2019 to 2029 and using an offset of 1, this gives identical results to moment.js so I've voted to close as off topic. You should post some sample dates that you think it returns incorrect values for. – RobG Mar 25 '19 at 04:15
  • Hi @RobG, when testing my example of 31/12/2018, or 30/12/19-31/12/19 I receive the error `Invalid write to global property "nYear"`? I copied your edits to my question which gave the error on any day selected within the year? – Ldweller Mar 28 '19 at 03:38
  • Then declare the property, perhaps you're running the code in strict mode? – RobG Mar 28 '19 at 08:43

0 Answers0