0

I've been working with dates in node for a while now. I had an issue where the date was giving the wrong date after adding months. I ran some tests.

const d = new Date('2021-05-01');
console.log(d); // 2021-05-01T00:00:00.000Z
d.setMonth(d.getMonth() + 1);
console.log(d); // 2021-05-31T00:00:00.000Z

I was confused why this wasn't just giving me 2021-06-01 after running

console.log(d.getMonth())

I realized it was returning 3 which is not May

Then I ran

console.log(d.toDateString())

Which gave me Fri Apr 30 2021

So my question is why does it make new Date('2021-05-01') actually April 30th?

  • 1
    I think there must be some other code that's missing here? I can't reproduce your problem. What else are you doing / using that may affect dates in some way? – Joseph Dec 22 '21 at 19:03
  • Nothing else in my code. I am running all that in a separate instance to my actual program and can reproduce on both – Cameron Hanton Dec 22 '21 at 19:05
  • 2
    Are you able to reproduce it in a codepen that you can link to? – Joseph Dec 22 '21 at 19:06
  • https://codepen.io/Hant0010/pen/dyVVOag – Cameron Hanton Dec 22 '21 at 19:11
  • 1
    That's strange, it outputs correctly for me ("Sat May 01 2021 01:00:00 GMT+0100 (British Summer Time)") – Joseph Dec 22 '21 at 19:13
  • ah okay well that answers it. Its a timezone thing. for me it outputs Fri Apr 30 2021 20:00:00 GMT-0400 (Eastern Daylight Time) but if I add a time 00:00:00 to the date it turns it to May – Cameron Hanton Dec 22 '21 at 19:15
  • 1
    Didn't expect it to work like that, but that must be it. It must be based off GMT and add or subtracts hours based on the local machine's time zone – Joseph Dec 22 '21 at 19:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240359/discussion-between-cameron-hanton-and-joseph). – Cameron Hanton Dec 22 '21 at 19:20

2 Answers2

0

I have node.js v17.3.0 and cannot recreate your problem (unfortunately I can't comment yet).

So my suggestion would be to check your node installation or perhaps reinstall node. After running your code in node REPL, I get Tue Jun 01 2021 as result. I live in Germany, I don't know if that helps.

andylib93
  • 133
  • 8
0

I ended up finding out that its because of timezones. I should of guess that, but if anyone else is in need of a fix you can simple add the time to the date to bring it to the actual date.

const date = new Date('2021-05-01 00:00:00');
  • '2021-05-01 00:00:00' is not a format supported by ECMA-262 so parsing is implementation dependent. Safari at least treats it as an invalid date. Replacing the central space with the letter "T" fixes that issue. – RobG Aug 30 '22 at 12:15