Skip to content

Instantly share code, notes, and snippets.

@Spacha
Last active January 7, 2018 16:36
Show Gist options
  • Save Spacha/67dea761ec14ef2db6db0b8227763bb6 to your computer and use it in GitHub Desktop.
Save Spacha/67dea761ec14ef2db6db0b8227763bb6 to your computer and use it in GitHub Desktop.
JS script which gives you week number. Used as a prototype for Date object.
Date.prototype.getWeek = function(){
// current week's Thursday
var curWeek = new Date(this.getTime());
curWeek.setDay(4);
// Get year's first week's Thursday
var firstWeek = new Date(curWeek.getFullYear(), 0, 4);
firstWeek.setDay(4);
return (curWeek.getDayIndex() - firstWeek.getDayIndex()) / 7 + 1;
};
/**
* Make a setDay() prototype for Date
* Sets week day for the date
*/
Date.prototype.setDay = function(day){
// Get day and make Sunday to 7
var weekDay = this.getDay() || 7;
var distance = day - weekDay;
this.setDate(this.getDate() + distance);
return this;
}
/*
* Returns index of given date (from Jan 1st)
*/
Date.prototype.getDayIndex = function(){
var start = new Date(this.getFullYear(), 0, 0);
var diff = this - start;
var oneDay = 86400000;
return Math.floor(diff / oneDay);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment