Home > Software design >  JS date giving wrong month
JS date giving wrong month

Time:12-23

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?

CodePudding user response:

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.

CodePudding user response:

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');
  • Related