Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
};
@mmdck
Copy link

mmdck commented Jul 6, 2014

good evening,
is that I can use this code in jquery-datepicker with 1.10.2.js and how please?

@johan
Copy link

johan commented Nov 11, 2015

I think you might want to add a line to getFullWeek just before the return to correct ISO dates currently coming out as W0 rather than the last week of the previous year:

    var y = d.getFullYear();
    if (w) return { y: y, w: w };
    return getWeeksInYear(y - 1); // 2000-01-01 = 1999W52, for instance

@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