Calculating week numbers in JS is surprisingly complex

Published on in JavaScript

JavaScript doesn't provide a native way to get the week number of a date. Just use a library instead.

It might be complex because week numbering itself is complicated.

In my case, I ended up using the getWeek() function from date-fns. This piece from its implementation on GitHub is amusing:

// Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1

I'm glad I haven't had to deal with date stuff much in the past.