Skip to content

Instantly share code, notes, and snippets.

@ynkdir
Created December 25, 2015 09:20
Show Gist options
  • Save ynkdir/1404089436de8b245ba5 to your computer and use it in GitHub Desktop.
Save ynkdir/1404089436de8b245ba5 to your computer and use it in GitHub Desktop.
weeknum.js
// うるう年
Date.prototype.isLeapYear = function() {
var y = this.getFullYear();
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
};
// 年間積算日
Date.prototype.getDayOfYear = function() {
var days1 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
var days2 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
var days = this.isLeapYear() ? days2 : days1;
return days[this.getMonth()] + this.getDate();
};
// 年間週番号
// 週は日曜日から始まる。
// 最初の水曜日を含む週が、その年の第1週である。
// すなわち1月4日が含まれる週が、その年の第1週である。
Date.prototype.getWeekNum = function() {
var firstday = new Date(this.getFullYear(), 0, 1);
var lastday = new Date(this.getFullYear(), 11, 31);
var isfirstweek = (this.getMonth() == 0 && this.getDate() - this.getDay() <= 1);
var islastweek = (this.getMonth() == 11 && this.getDate() + (6 - this.getDay()) >= 31);
if (isfirstweek && firstday.getDay() >= 4) {
return (new Date(this.getFullYear() - 1, 11, 31)).getWeekNum();
}
if (islastweek && lastday.getDay() <= 2) {
return 1;
}
var weeknum = Math.floor((this.getDayOfYear() + firstday.getDay() - 1) / 7) + 1;
if (firstday.getDay() >= 4) {
weeknum--;
}
return weeknum;
};
// 年間週番号
// ISO 8601
// 週は月曜日から始まる。
// 最初の木曜日を含む週が、その年の第1週である。
// すなわち1月4日が含まれる週が、その年の第1週である。
Date.prototype.getWeekNumISO8601 = function() {
// mon=0, ..., sun=6
var getDay = function(d) { return (d.getDay() + 6) % 7; };
var firstday = new Date(this.getFullYear(), 0, 1);
var lastday = new Date(this.getFullYear(), 11, 31);
var isfirstweek = (this.getMonth() == 0 && this.getDate() - getDay(this) <= 1);
var islastweek = (this.getMonth() == 11 && this.getDate() + (6 - getDay(this)) >= 31);
if (isfirstweek && getDay(firstday) >= 4) {
return (new Date(this.getFullYear() - 1, 11, 31)).getWeekNumISO8601();
}
if (islastweek && getDay(lastday) <= 2) {
return 1;
}
var weeknum = Math.floor((this.getDayOfYear() + getDay(firstday) - 1) / 7) + 1;
if (getDay(firstday) >= 4) {
weeknum--;
}
return weeknum;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment