简体   繁体   English

如何在 Javascript 中创建连续日期数组

[英]How to create an array of consecutive dates in Javascript

I wish to create an array of consecutive dates (without time) for the next two weeks.我希望为接下来的两周创建一系列连续日期(没有时间)。 The start date should be that of when the code is run (so not a hardcoded value).开始日期应该是代码运行的日期(所以不是硬编码的值)。 The way I've written it at the moment produces errors once the dates roll over into the next month.一旦日期滚动到下个月,我现在编写它的方式就会产生错误。 Both day and month jump ahead too far.日和月都跳得太远了。 Please see the output for an example.有关示例,请参阅 output。 Any advice would be appreciated thanks.任何建议将不胜感激。

var targetDate = new Date;
var current = targetDate.getDate();
var last = current + 1;

var startDate = new Date(targetDate.setDate(current)).toUTCString().split('').slice(0,4).join(' ');

var appointments = [startDate];

function createAppointmentsList() {
  while (appointments.length < 14) {
    var lastDate = new Date(targetDate.setDate(last)).toUTCString().split(' ').slice(0,4).join(' ');
    appointments.push(lastDate);
    last += 1;
  }
}

createAppointmentsList()

console.log(appointments);

which gives the output (see errors in final 2 entries):这给出了 output (请参阅最后 2 个条目中的错误):

[ 'Thu, 21 May 2020',
  'Fri, 22 May 2020',
  'Sat, 23 May 2020',
  'Sun, 24 May 2020',
  'Mon, 25 May 2020',
  'Tue, 26 May 2020',
  'Wed, 27 May 2020',
  'Thu, 28 May 2020',
  'Fri, 29 May 2020',
  'Sat, 30 May 2020',
  'Sun, 31 May 2020',
  'Mon, 01 Jun 2020',
  'Fri, 03 Jul 2020',
  'Mon, 03 Aug 2020' ]

when I want the output to be:当我希望 output 为:

[ 'Thu, 21 May 2020',
  'Fri, 22 May 2020',
  'Sat, 23 May 2020',
  'Sun, 24 May 2020',
  'Mon, 25 May 2020',
  'Tue, 26 May 2020',
  'Wed, 27 May 2020',
  'Thu, 28 May 2020',
  'Fri, 29 May 2020',
  'Sat, 30 May 2020',
  'Sun, 31 May 2020',
  'Mon, 01 Jun 2020',
  'Tue, 02 Jun 2020',
  'Wed, 03 Jun 2020' ]

Your targetDate is modified each time you call .setDate() .每次调用targetDate .setDate()时都会修改targetDate。 Once it rolls over into June, the day-of-month refers to that new month.一旦滚动到 6 月,当月日期指的是新的月份。

If you call new Date() instead each time through the loop, it will work.如果您每次通过循环调用new Date() ,它将起作用。

Check this if it helps you getting the result you need:如果它可以帮助您获得所需的结果,请检查此项:

function createAppointmentList() {
    const listLength = 14; // days
    let result = [];

    for(let i = 0; i < listLength; i++) {
        let itemDate = new Date(); // starting today
        itemDate.setDate(itemDate.getDate() + i);
        result.push(itemDate);
    }

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM