Using new Date() in MongoDB shell

I was testing the date data.
But I found something strange in the results of the new date().
I wonder why this result came out.

replica:PRIMARY> date = new Date()
ISODate(“2021-04-07T06:28:04.624Z”) // current time => right

replica:PRIMARY> date = new Date(2000,1,1)
ISODate(“2000-01-31T15:00:00Z”) // 2000/01/01 => wrong

I don’t think this is a mongodb problem, but I think it is my lack of knowledge about js. But I want to know the reason.

Hi @Kim_Hakseon,

You may wish to refer to this Date() constructor documentation.

Please see the following information when passing through Individual date and time component values as parameters into the Date() constructor:

Given at least a year and month, this form of Date() returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value ( 1 for day and 0 for every other component). The parameter values are all evaluated against the local time zone, rather than UTC.

In addition to this, the monthIndex is an Integer value representing the month, beginning with 0 for January to 11 for December. In your example, you have passed in a value of 1 for the monthIndex.

I would recommend using the ISO Date string format instead:

new Date(“2000-01-01”)
ISODate(“2000-01-01T00:00:00Z”)

Note: this constructor variation assumes UTC +0 (aka Z for Zulu time) for the date string.

A UTC offset can be included in the string, eg:

new Date(“2000-01-01T00:00+11:00”)
ISODate(“1999-12-31T13:00:00Z”)

Hope this helps!

Kind Regards,
Jason

3 Likes

Thanks to you @Jason_Tran.
I learned the mechanism for Date().

Jan is 0 in Date()…

And the reason why day is different is because Mongodb uses UTC and JS uses KST, which is the area where I am (Korea).
※ KST = UTC + 9h

So if you add 9 hours to the result, you get the desired result.

replica:PRIMARY> date = new Date(2000,1,1)
ISODate(“2000-01-31T15:00:00Z”) + 9hours
=> ISODate(“2000-02-01T00:00:00Z”)

1 Like