我想要一个包含本周和下周日期的数组。 我尝试用 for 循环和 while 循环来实现这个,但目前没有成功
getTwoWeeks = () => {
let twoWeeks = [];
let days = 14;
let today = new Date;
let calcFirst = today.getDate() - today.getDay();
let firstDayOfWeek = new Date(today.setDate(calcFirst));
for(let i=0; i<days; i++) {
twoWeeks.push( new Date(today.setDate(firstDayOfWeek + days[i])) )
}
console.log('twoWeeks===',twoWeeks )
}
最佳答案
您可以先计算本周的星期一,然后从那里迭代到 14 天。
const today = new Date();
const dayOfWeek = today.getDay();
const lastMonday = new Date(today.setDate(today.getDate() + (dayOfWeek * -1 + 1)));
for (let i = 1, d = lastMonday; i <= 14; i++, d.setDate(d.getDate() + 1)) {
console.log(new Date(d));
}
关于javascript - 获取本周和下一周的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61162012/