Reputation: 376
I currently have this code where I get the week number alongside the start/end day of that week with add and substract buttons:
Date.prototype.getWeekNumber = function() {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
};
var curr;
weekReset();
function display() {
start.textContent = curr;
end.textContent = endOfWeek(curr);
week.textContent = ("Week " + curr.getWeekNumber());
}
function weekReset() {
curr = startOfWeek(new Date());
display();
}
function startOfWeek(date) {
var start = new Date(date);
start.setHours(0, 0, 0, 0);
start.setDate(start.getDate() - start.getDay());
return start;
}
function endOfWeek(date) {
date = startOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
function weekPlus(weeks) {
curr.setDate(curr.getDate() + 7 * weeks);
display();
}
<div id="start">start</div>
<div id="end">end</div>
<div id="week">week</div>
<button onclick="weekReset()">current</button>
<button onclick="weekPlus(1)">add</button>
<button onclick="weekPlus(-1)">substract</button>
The problem is that it show's the current week number as 34;
starting on Sun Aug 27
ending on Sat Sep 02
... when this should be the week number 35.
So how can I change this function to count sunday as the first day of the week and saturday as the last day of the week?
Any help is appreciated.
Upvotes: 2
Views: 2913
Reputation: 147363
Your issue is here:
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
That code is for ISO weeks and adjusts Sunday's day number to 7 and sets the date to Thursday, where the week is Monday to Sunday.
You want weeks Sunday to Saturday and want the week of the Sunday, so use:
var dayNum = d.getUTCDay();
d.setUTCDate(d.getUTCDate() - dayNum);
which can be reduced to:
d.setUTCDate(d.getUTCDate() - d.getUTCDay());
Date.prototype.getWeekNumber = 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);
};
var c = new Date(2017,7,26);
console.log(c.getWeekNumber() + ':' + c.toString());
var d = new Date(2017,7,27);
console.log(d.getWeekNumber() + ':' + d.toString());
Upvotes: 3
Reputation: 2737
Your code d.setUTCDate(d.getUTCDate() + 4 - dayNum);
is setting your date back to three days earlier. I think that's the reason you are getting previous week number. I checked removing the code and it worked fine.
Upvotes: 1