Created
October 11, 2012 14:14
-
-
Save tborychowski/3872612 to your computer and use it in GitHub Desktop.
JS :: Get Week Number (ISO 8601)
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
//Returns ISO 8601 week number and year | |
Date.prototype.getFullWeek = function(){ | |
var jan1, w, d = new Date(this); | |
d.setDate(d.getDate()+4-(d.getDay()||7)); // Set to nearest Thursday: current date + 4 - current day number, make Sunday's day number 7 | |
jan1 = new Date(d.getFullYear(),0,1); // Get first day of year | |
w = Math.ceil((((d-jan1)/86400000)+1)/7); // Calculate full weeks to nearest Thursday | |
return {y: d.getFullYear(), w: w }; | |
}; | |
//Returns ISO 8601 week number | |
Date.prototype.getWeek = function(){ | |
return this.getFullWeek().w; | |
}; | |
var getWeeksInYear = function(y){ | |
return new Date(y,11,28).getFullWeek().w; | |
}; |
If I run this code today (4th January 2016), it returns week number 2 and not 1...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you might want to add a line to
getFullWeek
just before thereturn
to correct ISO dates currently coming out asW0
rather than the last week of the previous year: