Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active August 9, 2023 08:34
Show Gist options
  • Save vincentorback/8edffeca20e7a9e5e2a6 to your computer and use it in GitHub Desktop.
Save vincentorback/8edffeca20e7a9e5e2a6 to your computer and use it in GitHub Desktop.
getWeekNumber.js
function getWeekNumber(d) {
d = new Date(+d) // Copy date so don't modify original.
d.setHours(0, 0, 0, 0) // Reset hours.
d.setDate(d.getDate() + 4 - (d.getDay() || 7)) // Set to nearest Thursday: current date + 4 - current day number and make Sunday's day number 7
var yearStart = new Date(d.getFullYear(), 0, 1) // Get first day of year
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7) // Calculate full weeks to nearest Thursday
return weekNo // Return week number
}
var date = new Date()
var week = getWeekNumber(date)
@reetz
Copy link

reetz commented Feb 16, 2016

Thank you for that great function. I'm using it for some time now.

Lately I've run into a small issue. I'd suggest to change/add 3 bytes

--  d.setHours(0, 0, 0);
++  d.setHours(0, 0, 0, 0);

This year(2016) and some others have a special case. If the microseconds are not nulled the function may calculate 1 week too much.
All Years that start with a Friday (... 1999,2010,2016,2021 ...) are affected.

Yours sincerely
Michael Reetz

@srm80
Copy link

srm80 commented May 5, 2016

Thank you so much for commenting on this reetz. Lots of hours saved. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment