[英]Get the dates for this current week and the next one
I would like to have an array with dates of this current week and the next week.我想要一个包含本周和下周日期的数组。 I tried to implement this with a for loop and a while loop but didn't succeed at the moment我尝试使用 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 )
}
You can calculate first the Monday of the current week then iterate from there till 14 days.您可以先计算本周的星期一,然后从那里迭代到 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)); }
You can do this as follows:您可以按如下方式执行此操作:
getTwoWeeks = () => { let twoWeeks = []; let days = 14; let today = new Date(); twoWeeks.push(today) for(let i = 0; i < days-1; i++) { var next = new Date(); next.setDate(today.getDate()+1); twoWeeks.push(next); today = next; } console.log('twoWeeks===',twoWeeks ) } getTwoWeeks();
it looks like your are misusing your index "i" in the for loop.看起来您在 for 循环中滥用了索引“i”。 "days" is not an array, it is an integer. “days”不是一个数组,它是一个 integer。 Try the following:尝试以下操作:
let twoWeeks = []; let days = 14; let today = new Date; let calcDate = new Date(today.setDate(today.getDate() - today.getDay())); for(let i=0; i<days; i++) { calcDate.setDate(calcDate.getDate() + 1) twoWeeks.push(new Date(calcDate)) } console.log(twoWeeks)
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.