我试图确定给定的日期是该月的第一,第二,第三,第四或第五个工作日。因此,到目前为止,我已经尝试过如下代码:
Date.prototype.getWeekOfMonth = function(exact) {
var month = this.getMonth()
, year = this.getFullYear()
, firstWeekday = new Date(year, month, 1).getDay()
, lastDateOfMonth = new Date(year, month + 1, 0).getDate()
, offsetDate = this.getDate() + firstWeekday - 1
, index = 1 // start index at 0 or 1, your choice
, weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7)
, week = index + Math.floor(offsetDate / 7)
;
if (exact || week < 2 + index) return week;
return week === weeksInMonth ? index + 5 : week;
};
var weekOfMonth = date.getWeekOfMonth();
这是每月的第几周,而不是每月的第几周。
例如:2016-06-02
将以weekOfMonth = 2
的形式返回,而我想以1
的形式返回,因为它是该月的第一个星期日。我希望本月的第一,第二个工作日而不是本月的第一,第二个工作日。
答案 0 :(得分:0)
尝试这样。
function nthWeekdayOfMonth(weekday, date) {
var count = 1, i = 1;
var idate = new Date(date.getFullYear(), date.getMonth(), 1);
var ddate = date.getDate();
while (true) {
if (idate.getDay() === weekday || i >= ddate) {
count++;
if (i >= ddate) {
if (idate.getDay() != weekday && i >= ddate) {
count--;
}
break;
}
}
idate.setDate(idate.getDate() + 1);
i++;
}
return count;
}
var date = new Date("2016-06-02");
console.log(date.getFullYear(), date.getMonth());
console.log("Week of month starting with sunday is ",nthWeekdayOfMonth(0, date));