javascript calculate date from week number
function getDateOfWeek(w, y) {
var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week
return new Date(y, 0, d);
}
This uses the simple week definition, meaning the 20th week of 2013 is May 14.
To calculate the date of the start of a given ISO8601 week (which will always be a Monday)
function getDateOfISOWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
Result: the 20th week of 2013 is May 13, which can be confirmed here.
ISO Weeks
function weekDateToDate (year, week, day) {
const firstDayOfYear = new Date(year, 0, 1)
const days = 2 + day + (week - 1) * 7 - firstDayOfYear.getDay()
return new Date(year, 0, days)
}
Sorry if this is a little verbose but this solution will also return the Sunday after calculating the week number. It combines answers I've seen from a couple different places:
function getSundayFromWeekNum(weekNum, year) {
var sunday = new Date(year, 0, (1 + (weekNum - 1) * 7));
while (sunday.getDay() !== 0) {
sunday.setDate(sunday.getDate() - 1);
}
return sunday;
}