Languages
[Edit]
EN

JavaScript - get week number by date (year + month + day)

10 points
Created by:
Kenya-Spears
860

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

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join