Sometimes, we want to calculate date from week number in JavaScript.
In this article, we’ll look at how to calculate date from week number in JavaScript.
Calculate Date from Week Number in JavaScript
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)
.
Cconclusion
To calculate date from week number in JavaScript, we can use the JavaScript date setDate
and getDate
methods.