我如何使用 javascript/jquery 获取月份的周数?
例如:
第一周:2010 年 7 月 5 日。/周数 = 第一个星期一
前一周:2010 年 7 月 12 日。/周数 = 第二个星期一
当前日期:2010 年 7 月 19 日。/周数 = 第三个星期一
下周:2010 年 7 月 26 日。/周数 = 上周一
原文由 Prasad 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个老问题,这是我基于以下内容的跨浏览器解决方案:
所以在 2013 年 3 月:
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;
};
// Simple helper to parse YYYY-MM-DD as local
function parseISOAsLocal(s){
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
// Tests
console.log('Date Exact|expected not exact|expected');
[ ['2013-02-01', 1, 1],['2013-02-05', 2, 2],['2013-02-14', 3, 3],
['2013-02-23', 4, 4],['2013-02-24', 5, 6],['2013-02-28', 5, 6],
['2013-03-01', 1, 1],['2013-03-02', 1, 1],['2013-03-03', 2, 2],
['2013-03-15', 3, 3],['2013-03-17', 4, 4],['2013-03-23', 4, 4],
['2013-03-24', 5, 5],['2013-03-30', 5, 5],['2013-03-31', 6, 6],
['2013-04-01', 1, 1]
].forEach(function(test){
var d = parseISOAsLocal(test[0])
console.log(test[0] + ' ' +
d.getWeekOfMonth(true) + '|' + test[1] + ' ' +
d.getWeekOfMonth() + '|' + test[2]);
});
如果你不想的话,你不需要直接把它放在原型上。在我的实现中,6 表示“最后”,而不是“第六”。如果您希望它始终返回该月的实际周数,只需传递 true
。
编辑: 修复此问题以处理 5 周和 6 周的月份。我的“单元测试”,请随意分叉:http: //jsfiddle.net/OlsonDev/5mXF6/1/ 。
原文由 Olson.dev 发布,翻译遵循 CC BY-SA 4.0 许可协议
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
6 回答1.1k 阅读
添加具有
Last ...
的能力可能需要更多的黑客攻击……