Code4
Code4

Reputation: 93

Date is incrementing by a month after daylight saving is over in Javascript

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

Answers (4)

Md. Salahuddin
Md. Salahuddin

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

Jaromanda X
Jaromanda X

Reputation: 1

It has nothing to do with daylight savings, it has to do with what you are doing to currentDate

  • i == 0. CurrentDate.setDate = 28 + 0 = 28, Date is 28/Sep
  • i == 1. CurrentDate.setDate = 28 + 1 = 29, Date is 29/Sep
  • i == 2. CurrentDate.setDate = 28 + 2 = 30, Date is 30/Sep
  • i == 3. CurrentDate.setDate = 28 + 3 = 31, Date is 31/Sep, which becomes 01/Oct ... NOTE now CurrentDate month is OCTOBER
  • i == 4. CurrentDate.setDate = 28 + 4 = 32, Date is 32/Oct, becomes 1st November

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

Herku
Herku

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

Ben Guest
Ben Guest

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

Related Questions