Sometimes, we want to get the week of the year given a date.
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
Then we compute the week of the year by subtracting the timestamps of
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
week is 14.
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
It rounds down, so
week is 13.