Soutenez Time.now : Rejoignez notre Plan Premium pour une expérience sans publicité ! Soutenez-nous : Passez Premium sans pub !

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.

Instructions étape par étape

  1. Create a Date object and normalize it to midnight.
  2. Shift the date to the Thursday of its week (ISO weeks are defined by their Thursday).
  3. Count the days from January 1 of that Thursday's year and divide by 7, rounding up.
  4. The snippet on this page implements exactly that and logs the ISO week number.

Bon à savoir

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.