[javascript] Create an ISO date object in javascript

I have a mongo database set up. creating a new date object in mongoDb create a date object in ISO format eg: ISODate("2012-07-14T00:00:00Z")

I am using node.js to connect to mongo database and query the database. when ever I create a new date object (new Date()) in javascript its creates a javascript date object eg: Wed Mar 06 2013 14:49:51 GMT-0600 (CST)

Is there a way to create an ISO date object in javascript so that I can send the object directly to the mongoDb and perform date query

I am able to perform the below query in mongoDb

db.schedule_collection.find({
  start_date: { '$gte': new Date(2012, 01, 03, 8, 30) }
})

but cannot perform when I send in an javascript date object from node

The mongodb cookbook provides an python example to query the mongo database using datetime module, but does not provide any example use javascript.

Any help is appreciated. Thanking you in advance

This question is related to javascript node.js mongodb coffeescript

The answer is


try below:

var temp_datetime_obj = new Date();

collection.find({
    start_date:{
        $gte: new Date(temp_datetime_obj.toISOString())
    }
}).toArray(function(err, items) { 
    /* you can console.log here */ 
});

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)


Try using the ISO string

var isodate = new Date().toISOString()

See also: method definition at MDN.


I solved this problem instantiating a new Date object in node.js:...

In Javascript, send the Date().toISOString() to nodejs:...

var start_date = new Date(2012, 01, 03, 8, 30);

$.ajax({
    type: 'POST',
    data: { start_date: start_date.toISOString() },
    url: '/queryScheduleCollection',
    dataType: 'JSON'
}).done(function( response ) { ... });

Then use the ISOString to create a new Date object in nodejs:..

exports.queryScheduleCollection = function(db){
    return function(req, res){

        var start_date = new Date(req.body.start_date);

        db.collection('schedule_collection').find(
            { start_date: { $gte: start_date } }
        ).toArray( function (err,d){
            ...
            res.json(d)
        })
    }
};

Note: I'm using Express and Mongoskin.


In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)) So, simply convert it to a js Date by: new Date(ISOString);


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to coffeescript

React onClick and preventDefault() link refresh/redirect? How to run Gulp tasks sequentially one after the other How do I get the Back Button to work with an AngularJS ui-router state machine? How does Trello access the user's clipboard? Create an ISO date object in javascript How to rotate a 3D object on axis three.js? Exec : display stdout "live" Ternary operation in CoffeeScript How to use executables from a package installed locally in node_modules? Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?