Skip to content

Instantly share code, notes, and snippets.

@tborychowski
Created October 11, 2012 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tborychowski/3872612 to your computer and use it in GitHub Desktop.
Save tborychowski/3872612 to your computer and use it in GitHub Desktop.
JS :: Get Week Number (ISO 8601)
//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;
};
@ehannes
Copy link

ehannes commented Jan 4, 2016

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