我们如何获取本月的所有星期开始日期和结束日期?
下面的代码仅显示当前星期的开始日期和结束日期
var startOfWeek = moment().startOf("isoWeek").toDate();
var endOfWeek = moment().endOf("isoWeek").toDate();
console.log(startOfWeek)
console.log(endOfWeek)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js" integrity="sha512-Izh34nqeeR7/nwthfeE0SI3c8uhFSnqxV0sI9TvTcXiFJkMd6fB644O64BRq2P/LA/+7eRvCw4GmLsXksyTHBg==" crossorigin="anonymous"></script>
答案 0 :(得分:0)
只需在当前月份添加/减去7天,即可获得后续和之前的几周的信息。
let current = startOfWeek;
do {
current = current.subtract(7, "days"); //or .add(7, "days") to get next week
} while (current.month() === startOfWeek.month())
答案 1 :(得分:0)
这有趣吗? -不浪费时间
不确定从第一天开始还是下个月结束的几周要做什么
const d = new Date(),
month = d.getMonth(),
yyyy = d.getFullYear(),
end = new Date(yyyy,month+1,0).getDate();
const startEnd = Array.from(Array(end+1).keys()).slice(1)
.reduce((acc,day) => {
const d = new Date(yyyy,month,day,15,0,0,0);
if (d.getDay() === 1) acc.push({start:d});
else if (d.getDay() === 6 && acc[acc.length-1]) acc[acc.length-1]["end"] = d;
return acc
},[])
console.log(startEnd)
答案 2 :(得分:0)
该问题涉及ISO周,因此我想您希望当月的任何ISO周都在当月。您可以通过以下操作来实现:每月的1号,设置为上一个星期一(如果是星期一,则设置为同一天),然后在数周内进行迭代,直到到达下个月。例如
// Month is calendar month number
function getISOWeeksInMonth(month = new Date().getMonth() + 1, year = new Date().getFullYear()) {
// Start at 1st of month
let weekStart = new Date(year, month - 1, 1);
// Set to prior Monday
weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1);
// Get end of week
let weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 6);
// Get week number of 1st week
let weekNum = getWeekNumber(weekStart)[1];
// Create weeks array
let weeks = [];
while (weekStart.getMonth() < month) {
weeks.push({
weekNum : weekNum++,
start: new Date(weekStart),
end: new Date(weekEnd)
});
weekStart.setDate(weekStart.getDate() + 7);
weekEnd.setDate(weekEnd.getDate() + 7);
}
return weeks;
}
// Get ISO week number - from https://stackoverflow.com/a/6117889/257182
function getWeekNumber(d) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
return [d.getUTCFullYear(), weekNo];
}
// ISO weeks of current month
getISOWeeksInMonth().forEach(week => console.log(
'Week : ' + week.weekNum +
'\nStart: ' + week.start.toDateString() +
'\nEnd : ' + week.end.toDateString())
);
// ISO weeks in Feb 2021 (starts on a Monday)
getISOWeeksInMonth(2, 2021).forEach(week => console.log(
'Week : ' + week.weekNum +
'\nStart: ' + week.start.toDateString() +
'\nEnd : ' + week.end.toDateString())
);