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; | |
}; |
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
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
good evening,
is that I can use this code in jquery-datepicker with 1.10.2.js and how please?