let date = new Date('2020-04');
let month = date.getMonth() + 1;
This is giving me March not April, it is 1 month off, why is that?
If I use:
let date = new Date('2020-04');
month = date.getUTCMonth() + 1;
Then I get the correct answer. I’m in California. I need the answer to be correct wherever the user is in the world. i.e. I need April as the correct answer.
2
Answers
This creates a UTC date:
Note the
00.000Z
meaning "UTC" or "no offset".This gets that in your local time zone:
If you’re west of the GMT line, you’re going to get a value slightly lower, it’ll be X hours before that date, but if you’re east, it’ll be fine.
Your UTC solution is correct, as you’ll want a UTC month from a UTC date. The alternative is to specify a time with the time zone in it, like this:
Where you can see the UTC offset is now shown as instead of 00:00 you get 07:00.
getMonth()
now returns3
.In JavaScript, the Date object is affected by the local timezone of the user. When you create a new Date object like this: new Date(‘2020-04’), it is interpreted as being in the local timezone of the user. Since you’re in California, it’s using Pacific Time (PT).
In this case, due to daylight saving time, the date is affected by the timezone offset. In April, California is in Pacific Daylight Time (PDT), which is UTC-7, so when you create the date at midnight, it is actually 7 hours behind UTC. This means, in UTC, it’s still March 31st, 17:00.
However, when you call getUTCMonth(), it returns the month based on UTC, which is April. Since you want the answer to be correct wherever the user is in the world, you can continue using getUTCMonth() + 1.