Reputation: 13
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' ]
Upvotes: 0
Views: 1408
Reputation: 467
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;
}
Upvotes: 1
Reputation: 413702
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.
Upvotes: 1