JavaScript 计算当前日期是本年度及本月度第几周

// 计算当前日期在本年度的周数
Date.prototype.getWeekOfYear = function(weekStart) { // weekStart：每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
weekStart = (weekStart || 0) - 0;
if(isNaN(weekStart) || weekStart > 6)
weekStart = 0;

var year = this.getFullYear();
var firstDay = new Date(year, 0, 1);
var firstWeekDays = 7 - firstDay.getDay() + weekStart;
var dayOfYear = (((new Date(year, this.getMonth(), this.getDate())) - firstDay) / (24 * 3600 * 1000)) + 1;
return Math.ceil((dayOfYear - firstWeekDays) / 7) + 1;
}

// 计算当前日期在本月份的周数
Date.prototype.getWeekOfMonth = function(weekStart) {
weekStart = (weekStart || 0) - 0;
if(isNaN(weekStart) || weekStart > 6)
weekStart = 0;

var dayOfWeek = this.getDay();
var day = this.getDate();
return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
}

// 使用
var date = new Date(2011, 11, 31); // 注意：JS 中月的取值范围为 0~11
var weekOfYear = date.getWeekOfYear(); // 当前日期是本年度第几周
var weekOfMonth = date.getWeekOfMonth(); // 当前日期是本月第几周

// 2011 年度有几周
(new Date(2011, 11, 31)).getWeekOfYear();
// 2011 年度 1 月有几周
(new Date(2011, 0, 31)).getWeekOfMonth();