Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MongoDB shell new ISODate(0001-01-01) returns date 1901-01-01

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?

like image 943
Mr Grok Avatar asked Jul 24 '13 12:07

Mr Grok


People also ask

What is new date in MongoDB?

new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC. new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.

What Date format does MongoDB use?

MongoDB date format dd/mm/yyyy The date field is used to convert a date into a string. Optional, the format field is used for date format specification. Optional, the timezone field is used for the timezone of the operation result.

How is date stored in MongoDB?

The DATE type in MongoDB can store date and time values as a combined unit. The BSON Date type is a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

How does MongoDB compare ISO date?

Comparison Based on Date in MongoDB First, create a collection called 'data' using the document to further understand the concept. Use the find() function to show all the documents in a collection. The following is the date-based return query. Records with a creation date after 2018-05-19T11:10:23Z will be returned.


1 Answers

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.

like image 157
Derick Avatar answered Dec 31 '22 19:12

Derick