To calculate date from week number in JavaScript, we can use the JavaScript date setDate
and getDate
methods.
For instance, we can write:
const getSundayFromWeekNum = (weekNum, year) => {
const sunday = new Date(year, 0, (1 + (weekNum - 1) * 7));
while (sunday.getDay() !== 0) {
sunday.setDate(sunday.getDate() - 1);
}
return sunday;
}
console.log(getSundayFromWeekNum(10, 2021))
We create the getSundayFromWeekNum
function that takes the weekNum
and year
parameters that we use to get the Sunday of the given year and week number.
In the function, we create a JavaScript date with the Date
constructor with year
, 0, (1 + (weekNum - 1) * 7)
to get the date given weekNum
and year
.
Then we add a while loop to subtract 1 day from the sundday
date until we reach a Sunday.
Finally, we return that result.
Then when we console log, we get Sun Feb 28 2021 00:00:00 GMT-0800 (Pacific Standard Time)
.
One reply on “How to Calculate Date from Week Number in JavaScript?”
Unfortunately it’s wrong and it’s not following the standard ISO-8601 https://www.epochconverter.com/weeknumbers
For example, Week 1 2025 starts 30 December 2024 and ends 5 January 2025