Skip to content

Instantly share code, notes, and snippets.

@nsfmc
Created December 27, 2010 17:05
Show Gist options
  • Save nsfmc/756300 to your computer and use it in GitHub Desktop.
Save nsfmc/756300 to your computer and use it in GitHub Desktop.
adds an iso week count to the js Date function
/* getWeek returns an ISO 8601 week for any Date object.
*
* as far as i know, it handles all the weird boundary
* conditions that come up, even by a millisecond.
* no license, go nuts or whatever, or don't
* --marcos@generic.cx
*/
Date.prototype.getWeek = function() {
var fm = function(fullyear){
// return a date for the first monday in a year
var f = new Date(fullyear, 0, 1);
var d = f.getDay();
var m = (d > 4) ? 9 : 2;
f.setDate(m - d); // shift from 1st to first mon
return f;
}
var firstMon = fm(this.getFullYear());
if ((this - firstMon) < 0){ // if date precedes the first monday
firstMon = fm(this.getFullYear()-1);
}
return week = Math.floor(((this - firstMon) / 86400000)/7)+1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment