Sometimes, we want to get the week of the year given a date.
In this article, we’ll look at how to get the week of the year of a given date with JavaScript.
Using Native JavaScript Date Methods
One way to get the week of the year of a given date is to use JavaScript date methods to compute the week of the year of a given date ourselves.
For instance, we can write:
const now = new Date(2021, 3, 1);
const onejan = new Date(now.getFullYear(), 0, 1);
const week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);
console.log(week)
We have the now
date which we want to get the year of the week from.
Then we create the onejan
date with which is January 1 of the same year as now
.
Then we compute the week of the year by subtracting the timestamps of now
and onejan
.
And then we divide that by 86400000 to get the number of days difference between the 2 dates.
Then we add the day of the week plus 1 to get the actual number of days difference.
Then we divide that by 7 to get the number of weeks difference.
And we round that number up to the nearest integer with Math.ceil
.
Therefore, week
is 14.
Use Moment.js
A simpler way to get the week number of the year from a given date is to use moment.js.
To use it, we write:
const now = new Date(2021, 3, 1);
const week = moment(now).format('W')
console.log(week)
We pass in the now
date to moment
to create a moment object.
Then we call format
with the 'W'
formatting tag to get the week of the year of now
.
It rounds down, so week
is 13.
Conclusion
We can use JavaScript date methods or use moment.js to get the week of the year.