getMonth returns incorrect value

Viewed 86

I have some tests that test the getMonth method on my code.

For everything to go well, I set my date to UTC 0, if I put for example Date.UTC(new Date (2021, 0, 1)) I have a string 2021-01-01T00:00:00.000Z

But when I upload it to gitlab and it passes the tests there, the result is 2021-01-01T00:00:00.000Z too, but getMonth() give me 12 value.

Can you help me please?

The following example returns on my tests 1 but 12 on gitLab terminal.

console.log(
    "original time month__ ",
    new Date(
       new Date(year, month - 1, 1).getTime() -
          new Date().getTimezoneOffset() * 60 * 1000
    ).getMonth() + 1
);
1 Answers

You must be using getUTCMonth instead of getMonth for UTC

Look at the console screenshot for explanation. (Testing from India +05:30)

enter image description here

let demo = new Date('2021-12-31T20:00:00.000Z'); //TZ: +05:30
console.log('getMonth(): ', demo.getMonth());
console.log('getUTCMonth(): ', demo.getUTCMonth());

Related