Reputation: 93
im trying to add dates to an array, all works well, date is incremented by one but after the first of october the javascript increments it by a month.
var currentDate = new Date();
var startDate = new Date();
for (var i = 0; i <= 4; i++) {
currentDate.setDate(startDate.getDate() + i);
console.log (currentDate);
}
OUTPUT:
Upvotes: 0
Views: 166
Reputation: 1072
Try with setTime() with adding number of days in milliseconds instead of setDate() to add days to a date.
var currentDate = new Date();
var startDate = new Date();
for (var i = 0; i <= 4; i++) {
currentDate.setTime(startDate.getTime() + (i*86400000));
console.log(currentDate);
}
Upvotes: -1
Reputation: 1
It has nothing to do with daylight savings, it has to do with what you are doing to currentDate
etc
You can achieve what you want without needing to worry about how many days in a month with this
var currentDate = new Date();
var startDate = new Date();
for (var i = 0; i <= 4; i++) {
currentDate.setDate(currentDate.getDate() + 1); // <<<===
// ^^^^^^^^^^^ ^
console.log (currentDate);
}
Upvotes: 3
Reputation: 7666
I think i figured out the problem:
First you need to recognise what setDate
actually does. It sets the day of the month. So lets iterate through the loop and keep track of the Date object:
currentDate => {d: 28, m: 9}
startDate => {d: 28, m: 9}
currentDate.setDate(28 + 1)
currentDate => {d: 29, m: 9}
currentDate.setDate(28 + 2)
currentDate => {d: 30, m: 9}
currentDate.setDate(29 + 3)
currentDate => {d: 1, m: 10} // month changed!!!
currentDate.setDate(29 + 4)
// month changed again since the old month
// is still 10, not 9
currentDate => {d: 1, m: 11}
Try using setTime()
and getTime()
or completely delegate date operations to a liblary like Moment.js
Upvotes: 0
Reputation: 1558
Try it without startDate:
var currentDate = new Date();
for (var i = 0; i <= 4; i++) {
currentDate.setDate(currentDate.getDate() + 1); // Notice + 1 not + i
console.log(currentDate);
}
Upvotes: 0