Somnium Somnium - 4 months ago 41
Javascript Question

In Javascript "d.setDate(d.getDate() + 1)" gives wrong answer in days when was time change

I have following code:

var d = new Date('2016-03-27');
console.log(d.getDate(), d);
d.setDate(d.getDate() + 1);
console.log(d.getDate(), d);


Which gives incorrect answer:

27 Date 2016-03-27T00:00:00.000Z
28 Date 2016-03-27T23:00:00.000Z


Note on the second line dates does not match. It seems that it adds 24 hours instead one day. Locale is Latvia and in that day was time change by 1h.

Correct answer will be:

28 Date 2016-03-28T00:00:00.000Z


How I can work around this?

Answer

Since you are working with UTC format dates, and you want to ignore local timezone changes such as daylight savings time, you should always use getUTCDate() and setUTCDate(). UTC has no daylight savings.

var d = new Date('2016-03-27');
console.log(d.getUTCDate(), d);
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.getUTCDate(), d);

Also consider JavaScript date libraries such as moment.js if you have more complex requirements.