2

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?

Somnium
  • 1,059
  • 1
  • 9
  • 34
  • 2
    The answer is correct - your local timezone shifts during that night. So your local time is properly increased by exactly one day, but its representation in UTC differs. – zerkms Aug 01 '16 at 10:55
  • @zerkms It's not correct - from fuction name I expect to add one day, not 24 hours like it does. – Somnium Aug 01 '16 at 10:56
  • You're confusing data with its representation: you add 1 day to the **LOCAL TIME**. And it's added properly. Then it is formatted to UTC. UTC does not have notion of summer time, while your local time does have. – zerkms Aug 01 '16 at 10:57
  • @zerkms No matter how you name it - correct or not. It's not returning answer I need. How I can fix so it only changes date ignoring time? – Somnium Aug 01 '16 at 10:58
  • "It's not returning answer I need" --- well, that's because you did not express your intention clearly to JS. What if you use `var d = new Date('2016-03-27T00:00:00.000Z');` instead? – zerkms Aug 01 '16 at 11:00
  • @zerkms That doesn't change anything (tested). – Somnium Aug 01 '16 at 11:01
  • 1
    Try d.setUTCDate() instead of d.setDate() – Owen Aug 01 '16 at 11:03
  • @Owen It works, thank you! Can you add an answer so I accept it? However, I'm not sure, will it work on all days or there will be also some days when time changes and result will be unexpected? – Somnium Aug 01 '16 at 11:06
  • 1
    Yes - changes in the other direction could be affected unless you also use getUTCDate(). Answered below. – Owen Aug 01 '16 at 11:12

1 Answers1

6

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.

Owen
  • 1,527
  • 11
  • 14