缘由
某天接到需求,要根据月份算当前月有几周,按周获取数据,于是乎各种百度,但是好多方法的实现实太复杂了,虽然想无脑搬运,但是我觉得搬运的前提还是要自己能看懂,之后在一个小哥哥的帖子上想到了个简单的实现的方法,如有bug,请各位指教,
代码
function weeks (now_month) {
let week_array = [];
let today = new Date(Date.parse(now_month));
let year = today.getFullYear();
let month = today.getMonth();
let i = 0;
let start = new Date(year, month, 1); // 得到当月第一天
let end = new Date(year, month+1, 0); // 得到当月最后一天
// 循环每周最后天叠设置为第一天,直到最后一天小于当月的最后一天
while (start <= end ) {
const monday = new Date(start.getTime());
const sunday = new Date(start.getTime());
monday.setDate(monday.getDate()+1-monday.getDay());
sunday.setDate(sunday.getDate()+7-sunday.getDay());
week_array.push(
[monday,sunday]
)
start = sunday;
}
return week_array;
}
输入 weeks("2022-03") 得到了正确的输出
学无止境
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。