Home > Net >  javascript getMonth() off by 2?
javascript getMonth() off by 2?

Time:10-02

I understand that getMonth() is zero indexed so, for example, June is 5. But I'm getting that it's 'off' by 2 in some situations.

myDate = new Date(1622513190000)
month = myDate.getMonth()

console.log(myDate)
console.log(month)

Returns:

2021-06-01T02:06:30.000Z

4

Anyone have an idea why this is returning 4 and not 5? I'm using node v14.15.5 and am getting the expected result for other dates (September is 8, August is 7)

Thanks!

CodePudding user response:

Hi and welcome here :)

Working with dates and timezone is a bit tricky, everyone here can attest it. For general information, I suggest you to read this article about Coordinated universal time.

The Z you can see in myDate value means Zulu time, military name for UTC±00:00, the reference timezone. ±00:00 represents an eventual offset with the Zulu time.

After having gone crazy about this question, I advice you to :

  • always get and store dates in Zulu format, and then compute time lapse with them
  • you can show users local dates, but it's only to display them. If you have to compute with a user input, first get the UTC equivalent (as @RobG advised).

Good luck ! :)

  • Related