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?