0

I want to represent the first of a given month, say 1st of Septemeber 2020. When I do this in my console, I get the below output:

$ node
> new Date(2020, 8, 1)
2020-08-31T23:00:00.000Z

How come it returns 2020-08-31 instead of 2020-08-01? What am I doing wrong?

gullerg
  • 371
  • 2
  • 15

2 Answers2

0

The output

2020-08-31T23:00:00.000Z

is ISO format, and the Z shows the date is in UTC. When you call the Date constructor, it is using your browser timezone by default, which I can assume is +01:00. Moreover, month indice in the constructor is zero-based.

If what you want is the beginning of the month in UTC, you can do:

d = new Date(Date.UTC(2020, 8, 01))
d.toISOString()
"2020-09-01T00:00:00.000Z"
Derlin
  • 9,572
  • 2
  • 32
  • 53
  • Okay thanks, I get what you're saying - I was reading the output date with zero indexed months in mind although it shouldn't be read like that. And yeah, the timezone was confusing me slightly too. Thanks for your help – gullerg Aug 11 '20 at 15:54
  • 1
    This answer is the same as in the identified duplicate and should not be marked as the answer... – Heretic Monkey Aug 11 '20 at 15:59
0

try

new Date(2020, 7, 1)

because date object is count from 0-11 no 1-12

TalOrlanczyk
  • 1,205
  • 7
  • 21