0

Ok, I have a weird issue. I'm just starting with Node and MongoDB and at first I got a little bit confused by the whole ISO time vs local time and I ran into a weird issue.

I got a string with a date, and although it's overkill, I manually splitted it and pass it to the "new Date()" constructor, it adds one month to all the dates.

This is my code:

str = str.split(' ')
str[0] = str[0].split('-')
str[1] = str[1].split(':')
console.log(str)
str = new Date(str[0][0],str[0][1],str[0][2],str[1][0],str[1][1],str[1][2]);
console.log(str)
console.log(str.toString())

And this is the output:

[ [ '1970', '01', '01' ], [ '00', '00', '00' ] ]  //First UNIX date splitted into a yyyy, mm, dd, HH, MM, DD
1970-02-01T03:00:00.000Z                          //After the Date object is generated, note that the month is now "02"
Sun Feb 01 1970 00:00:00 GMT-0300 (hora de verano de Chile) //The date returned to local time. Note that the month change was maintained.

Am I doing something wrong in changing types? Does it have to do with something aside the code?

The whole purpose is to insert the Date object into a mongodb collection in ISO format, and then query it back and show it in local time.

  • 1
    The month on the `Date` class is zero based. January is `0`. So if you are passing in a month of `1`, you are telling the date that it is febuary. – Taplar Dec 09 '20 at 20:40

1 Answers1

4

According to the documentation for Date, the month is zero-indexed. So it's not adding a month, you're just passing the wrong value because the month in your string is one-indexed.

Subtract 1 from that value:

new Date(str[0][0], str[0][1] - 1, str[0][2], str[1][0], str[1][1], str[1][2]);
David
  • 208,112
  • 36
  • 198
  • 279
  • Wow, although I missed looking at the Date documentation (rookie mistake) I'm surprised that I couldn't find an answer by directly searching on google. Thanks! – Sebastian Araneda Dec 09 '20 at 20:44