如何创建一个 for 循环来收集几个月之间一周中的每一天?
所以,我需要收集本周的所有日子,从周日到周六,我开始编写一个代码,该代码采用实际日期并创建一个 for 循环将每一天推入数组中,问题是在像这样的几周(在一个月内开始并在另一个月内结束)代码将无法工作。
这是代码:
const createWeek = async() => {
const d = new Date();
let month = d.getMonth() + 1;
let year = d.getFullYear();
const inicialDate = d.getDate() - d.getDay();
const lastDate = inicialDate + 6;
console.log(d, 'current date')
let firstDay = new Date(d.setDate(inicialDate));
let lastDay = new Date(d.setDate(lastDate))
let week = []
for (let i = firstDay.getDate(); i <= lastDay.getDate(); i++) {
week.push(`${i.toLocaleString().length <= 1 ? "0" + i : i}${month.toLocaleString().length <= 1 ? "0" + month : month}${year}`);
}
return week;
}
所以我知道问题是因为在我的 for 循环中,一周的第一天大于一周的最后一天,但我不知道如何处理。我想知道最好的方法是什么。
感谢您的帮助。
So, i need to gather all days the current week, from Sunday to Saturday, i started making a code that takes the actual date and make a for loop to push each day into a array, the problem is that on weeks like this one (that begins in one month and finish in another) the code wont work.
Here is the code:
const createWeek = async() => {
const d = new Date();
let month = d.getMonth() + 1;
let year = d.getFullYear();
const inicialDate = d.getDate() - d.getDay();
const lastDate = inicialDate + 6;
console.log(d, 'current date')
let firstDay = new Date(d.setDate(inicialDate));
let lastDay = new Date(d.setDate(lastDate))
let week = []
for (let i = firstDay.getDate(); i <= lastDay.getDate(); i++) {
week.push(`${i.toLocaleString().length <= 1 ? "0" + i : i}${month.toLocaleString().length <= 1 ? "0" + month : month}${year}`);
}
return week;
}
So i know that the problem is because in my for loop the first day of the week is bigger than the final day of the week, but i dont know how to deal with that. I want to know what is the best aproach to this.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议使用
Date。 setDate()
来调整每天,这也会正确调整月份。我们首先获取 weekStart 日,从 currentDate.getDate() 中减去 currentDay.getDay() 的结果,并将其用作 setDate() 的输入。
然后我们可以使用
Array.from ()
生成我们的 7 天列表。我建议首先创建一个包含七个日期的数组,然后创建一个自定义格式化函数,例如用于此目的的
formatDate()
。这使我们能够分离创建和显示日期的逻辑。I'd suggest using
Date.setDate()
to adjust each day, this will adjust the month correctly as well.We start by getting the weekStart day, by subtracting the result of currentDay.getDay() from currentDate.getDate() and using this as the input to setDate().
We can then use
Array.from()
to generate our list of seven days.I'd suggest first creating an array of seven dates, then creating a custom formatting function, e.g.
formatDate()
for this purpose. This allows us to separate the logic of creating and displaying the dates.