如何创建一个 for 循环来收集几个月之间一周中的每一天?

发布于 2025-01-11 11:51:07 字数 819 浏览 0 评论 0原文

所以,我需要收集本周的所有日子,从周日到周六,我开始编写一个代码,该代码采用实际日期并创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埖埖迣鎅 2025-01-18 11:51:07

我建议使用 Date。 setDate() 来调整每天,这也会正确调整月份。

我们首先获取 weekStart 日,从 currentDate.getDate() 中减去 currentDay.getDay() 的结果,并将其用作 setDate() 的输入。

然后我们可以使用 Array.from () 生成我们的 7 天列表。

我建议首先创建一个包含七个日期的数组,然后创建一个自定义格式化函数,例如用于此目的的 formatDate() 。这使我们能够分离创建和显示日期的逻辑。

function createWeek(currentDay = new Date()) {
    const weekStart = new Date(currentDay);
    weekStart.setDate(currentDay.getDate() - currentDay.getDay());
    return Array.from( { length: 7 }, (v,k) => { 
        const dt = new Date(weekStart);
        dt.setDate(weekStart.getDate() + k);
        return dt;
    })
}

function formatDate(date) {
    return [date.getDate(), date.getMonth() + 1, date.getFullYear()]
     .map(n => (n + '').padStart(2, '0'))
     .join('');
}

const weekDates = createWeek();
console.log('Formatted dates:')
for(let date of weekDates) {
    console.log(formatDate(date));
}
.as-console-wrapper { max-height: 100% !important; }

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.

function createWeek(currentDay = new Date()) {
    const weekStart = new Date(currentDay);
    weekStart.setDate(currentDay.getDate() - currentDay.getDay());
    return Array.from( { length: 7 }, (v,k) => { 
        const dt = new Date(weekStart);
        dt.setDate(weekStart.getDate() + k);
        return dt;
    })
}

function formatDate(date) {
    return [date.getDate(), date.getMonth() + 1, date.getFullYear()]
     .map(n => (n + '').padStart(2, '0'))
     .join('');
}

const weekDates = createWeek();
console.log('Formatted dates:')
for(let date of weekDates) {
    console.log(formatDate(date));
}
.as-console-wrapper { max-height: 100% !important; }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文