Is the output of MongoDB's ISODate() function always distinct from that of the Date()

After reviewing the documentation, my understanding was that ISODate simply wrapped the Date constructor. However, I've encountered issues when working with dates very far in the past. For example:

new Date(-8640000000000000);                          // Mon Apr 19 -271821 18:00:00 GMT-0600 (Mountain Daylight Time)
new Date(-8640000000000000).toISOString();            // -271821-04-20T00:00:00.000Z
ISODate(new Date(-8640000000000000).toISOString());   // Wed Sep 03 2719 18:00:00 GMT-0600 (Mountain Daylight Time)

It's puzzling why the first date and the last date do not match. There seems to be some kind of overflow occurring. Also, what are the limits of dates that MongoDB can handle?

Edit: Interestingly, the following works as expected:

new Date( new Date(-8640000000000000).toISOString()); // Mon Apr 19 -271821 18:00:00 GMT-0600 (Mountain Daylight Time)

Answer №1

Information regarding the range aspect can be found in the documentation.

Internally, Date objects are represented as a 64-bit integer indicating the number of milliseconds since the Unix epoch (Jan 1, 1970). This allows for a range of dates approximately 290 million years into the past and future.

Let's dissect the given details by running everything on the mongo shell.

new Date(-8640000000000000); //ISODate("-271821-04-20T00:00:00Z")

new Date(-8640000000000000).toISOString(); // -271821-04-20T00:00:00.000Z

ISODate(new Date(-8640000000000000).toISOString()); //ISODate("2719-09-04T00:00:00Z")

Analyzing the output from the last date provided, after converting new Date(-8640000000000000).toISOString(), the result -271821-04-20T00:00:00.000Z goes through the ISODate function.

This outcome is then subjected to the regular expression within the ISO Date function, designed for typical date formats.

/(\d{4})-?(\d{2})-?(\d{2})(T (:?(\d{2})(:?(\d{2}(.\d+)?))?)?(Z|([+-])(\d{2}):?(\d{2})?)?)?/

Running the regex against the date yields three groups.

Full match  0-9 `271821-04`

Group 1.    0-4 `2718`
Group 2.    4-6 `21`
Group 3.    7-9 `04`

Thus, ISODate feeds these values to the javascript Date.UTC constructor, resulting in a year of 2718, month of 21 (interpreted as 1 year and 9 months), and day of the month as 4. Consequently, the year is adjusted to 2719, the month to 9, and the day remains as 4.

Conclusively, the final date output is 2719-09-04.

Answer №2

Exploring Date Manipulation in MongoDB Shell with Meteor

meteor:PRIMARY> new Date(1479424285700)
ISODate("2016-11-17T23:11:25.700Z")
meteor:PRIMARY> ISODate(new Date(1479424285700).toISOString());
ISODate("2016-11-17T23:11:25.700Z")

Both queries return the same date, showcasing the consistency of date handling in MongoDB Shell.

Questioning the Purpose of Passing "-8640000000000000" to the Date Constructor

The JavaScript Date object represents a precise moment in time, measured in milliseconds since January 1, 1970, UTC.

Cautionary Note: Negative values passed to the constructor could yield unexpected outcomes due to potential non-specification considerations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on incorporating geolib into React Native for distance calculation of two locations

Is there a simple way to calculate the distance between Longitude and Latitude in react native? I have the coordinates of my current location and destination, but keep encountering errors when attempting to use geolib for this calculation. I attempted to ...

Is it possible to delay Vue rules from validating until a user interacts with an element?

For a project I am working on, I have implemented a v-date-picker where users can select a departure date and a return date. Interestingly, while most of the input field validations only occur after user interaction, the departure date picker displays an e ...

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...

Display the entire dataset retrieved from MongoDB and utilize the doT.js templating engine for rendering

I am facing an issue with extracting data from mongodb and passing it to the view. Despite all my efforts, only one record out of 10000 is showing up instead of all of them. I believe I am very close to resolving this problem but unfortunately, I am stuck. ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...

How to use Mongoose to update a MongoDB document with multiple arrays of nested documents

If I have a document structured like the following: { "personId": 13998272, "address": [ { "addressType": "HOME", "streetNo": 21, "addressLine1": "LORRAINE AVENUE", "addressLine2": "EDGEWATER", "city": "KINGSTON", ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

Whenever I attempt to run my script, the console on replit fails to function properly

As a complete beginner to Javascript, I'm having trouble getting my script to respond when I try to execute it. It just moves on to the next line and waits for me to type 'node index.js' again. I've included 2 images in an Imgur album - ...

The onClick function for a button is not functioning properly when using the useToggle hook

When the button is clicked, it toggles a value. Depending on this value, the button will display one icon or another. Here is the code snippet: export const useToggle = (initialState = false) => { const [state, setState] = useState(initialState); c ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

Utilizing CSS transitions to smoothly adjust the width of an element until it completely fills the container div in ReactJS

import React from 'react'; import PropTypes from 'prop-types'; import SearchIcon from '@material-ui/icons/Search'; import InputBase from '@material-ui/core/InputBase'; import { AccountCircle } from '@material-ui ...

Interrogating a time field utilizing ReactiveMongo and Play JSON

Searching for the equivalent of this query using ReactiveMongo in conjunction with Play Framework & JSON has been a challenge for me: db.getCollection('people').find({'refreshed': {$gt: ISODate('2017-01-01')}}) My attempt so ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

Experiencing issues with recognizing HTML DOM functions during Jest testing

I encountered an issue that reads as follows: TypeError: document.querySelector is not a function This error occurred in the line below: selectElement = document.querySelector('#selectbox'); The purpose of this line is to retrieve the selec ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Here is an example of how to transfer a value from PHP to a jQuery function in the code snippet provided

This is an example of my code. It is functioning properly even without passing a value. function displayMessage(text) { alert(text); } <button type="button" id="button" class="btn btn-success" onclick="displayMessage("Hello");"> Click Me </ ...

Combining array outputs from both Promise.all and map functions

Hey, it might seem silly, but it's late and I'm struggling with this issue. My goal is to gather statistics for different types of values and store them in an array. However, the problem lies in the final result: // Data this._types = [{ id: 1, ...

Guide to dynamically add data to two columns

I have a challenge with organizing multiple inputs into rows with two columns each, ensuring that each input is appended to the appropriate side (50% for each column unless there's an odd number of inputs). Currently, the inputs are being added to se ...