Why MongoDB shell new ISODate(0001-01-01) returns date 1901-01-01
mongo-shell, mongodb
Solution
Internally, `new ISODate` really means:
Date.UTC(year, month, date, hour, min, sec, ms);
IE, MongoDB splits up the string into elements with a regular expression (Line 60 at https://github.com/mongodb/mongo/blob/master/src/mongo/shell/types.js#L56)
The JavaScript Date object has a few different initialisers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax). If you use:
new Date("0001-01-01T:00:00:00");
Then the four digit year `0001` is not parsed or interpreted, but when you use it like MongoDB does:
Date.UTC( parseInt("0001") )
Then special rules apply for the years 00-99 apply. The docs at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date_instances slightly hint at this.
There is a MongoDB server ticket already at https://jira.mongodb.org/browse/SERVER-8164, please vote for it.
Problem
In MongoDB Shell on windows if you run a query with a value of ``` new ISODate('0001-01-01T00:00:00Z') ``` it actually seems to search for ``` new ISODate('1901-01-01T00:00:00Z') ``` If you enter "new ISODate('0001-01-01T00:00:00Z')" directly in the Mongo Shell you can see this conversion taking place as it returns ISODate("1901-01-01T00:00:00Z"). Oddly, when you use "new Date" instead of "new ISODate" by entering: ``` new Date('0001-01-01T:00:00:00Z') ``` it returns ISODate("0001-01-01T00:00:00Z") which is correct. Both are supposed to return an ISODate according to the docs and to my mind should act identically. Does anyone know why they don't and whether it's a bug or a feature?