Public
Edited
Jun 8, 2023
Importers
Insert cell
Insert cell
// https://stackoverflow.com/questions/9045868/javascript-date-getweek#comment105235371_9047794
// dowOffset = 1 => Monday

function getWeek(date, dowOffset = 1) {
const newYear = new Date(date.getFullYear(), 0, 1);
let day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = day >= 0 ? day : day + 7;
const daynum =
Math.floor(
(date.getTime() -
newYear.getTime() -
(date.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) /
86400000
) + 1;
//if the year starts before the middle of a week
if (day < 4) {
const weeknum = Math.floor((daynum + day - 1) / 7) + 1;
if (weeknum > 52) {
const nYear = new Date(date.getFullYear() + 1, 0, 1);
let 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*/
return nday < 4 ? 1 : 53;
}
return weeknum;
} else {
return Math.floor((daynum + day - 1) / 7);
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more