Last active
August 9, 2023 08:34
-
-
Save vincentorback/8edffeca20e7a9e5e2a6 to your computer and use it in GitHub Desktop.
getWeekNumber.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
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
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