Week numbers in JavaScript
To get the current ISO 8601 week number in JavaScript, use the following code snippet:
// Calculate ISO Week
const d = new Date();
d.setHours(0,0,0,0);
d.setDate(d.getDate() + 4 - (d.getDay()||7));
const yearStart = new Date(d.getFullYear(),0,1);
const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1)/7);
console.log(weekNo);
* Ensure your system or application regional settings are set to follow ISO 8601 standards (weeks start on Monday) if the output varies.
Step-by-Step Instructions
- Create a Date object and normalize it to midnight.
- Shift the date to the Thursday of its week (ISO weeks are defined by their Thursday).
- Count the days from January 1 of that Thursday's year and divide by 7, rounding up.
- The snippet on this page implements exactly that and logs the ISO week number.
Good to Know
JavaScript has no built-in ISO week function. If you already use a date library, prefer its implementation: Luxon has DateTime.now().weekNumber, date-fns has getISOWeek(), and Day.js has the isoWeek plugin.