0

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. 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):

[ '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:

[ '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' ]
2
  • Does this answer your question? Javascript - get array of dates between 2 dates Commented May 21, 2020 at 13:02
  • As @pointy said, var lastDate = new Date(new Date().setDate(last)).toUTCString().split(' ').slice(0,4).join(' '); Commented May 21, 2020 at 13:34

2 Answers 2

1

Your targetDate is modified each time you call .setDate(). Once it rolls over into June, the day-of-month refers to that new month.

If you call new Date() instead each time through the loop, it will work.

Sign up to request clarification or add additional context in comments.

Comments

1

Check this if it helps you getting the result you need:

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

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

    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.