EN
JavaScript - get week number by date (year + month + day)
10
points
In this short article, we would like to show how to get current week number for indicated date using JavaScript.
In the example we assume that:
- each week starts on Sunday and ends on Saturday,
- partial weeks are taken into account also (e.g. first and last weeks of year).
Practical example:
// ONLINE-RUNNER:browser;
const getWeekNumber = (year, month, day) => {
const a = new Date(year, 0, 1);
const b = new Date(year, month, day);
return Math.ceil(((b - a) / 86400000 + 1 + a.getDay()) / 7);
};
// Usage example:
// Month: 0 - January, ..., 11 - December
console.log(getWeekNumber(2023, 0, 1)); // 1
console.log(getWeekNumber(2023, 9, 28)); // 43
console.log(getWeekNumber(2023, 11, 31)); // 53