27

I want to compare date from MongoDB and my date.

Also i read this and this post and I did not find an answer.

My Code :

  today: function() {
    var today = moment().format();
    return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
  },

createdAt = moment().format();// in MongoDB

As a result this construction doesn't work, but if i compare lie this :

var today = moment().format();
var daystart  = moment().startOf('day').format();
if (daystart > today){
  console.log ("YES");
}
else if (daystart < today)console.log ("NO");

Return

"NO"

Anybody help ?

EDIT :

  today: function() {
    var today = moment().toDate();
    var daystart  = moment().startOf('day').toDate();
    // console.log(today + daystart);
    return Posts.find({createdAt : { $gt : today}}) 
  },
  week: function() {
          var today = new Date();
      return Posts.find({createdAt : { $lt : today}}) 
  },
  month: function() {
            var today = new Date();
      return Posts.find({createdAt : { $ne : today}}) 
  }

createdAt = new Date();
Community
  • 1
  • 1
nl pkr
  • 656
  • 1
  • 11
  • 21

2 Answers2

29

The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:

today: function() {
    var now = moment().toDate();
    return Posts.find({createdAt : { $gte : now }});
}
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 5
    And here was the rest of us who thought you had to call [`.toDate()`](http://momentjs.com/docs/#/displaying/as-javascript-date/) on a moment object to return a JavaScript Date object which is valid for serialization. – Blakes Seven Jul 17 '15 at 12:24
  • in mongo i must write like this `createdAt = moment()` or `createdAt = moment().toDate()` – nl pkr Jul 17 '15 at 12:48
  • @nlpkr You could either write it as `createdAt = moment().toDate()` or simply `createdAt = new Date();` – chridam Jul 17 '15 at 12:50
  • @nlpkr In Mongo shell, you could create a variable that holds the current date and time and use it in the query like `var now = new Date(); db.posts.find({createdAt: {$gt: now}})`, is this what you are after? – chridam Jul 17 '15 at 12:59
  • 1
    I was using `.toISOString()` and was trying to debug since 2 hours... :facepalm:, finally this got the job done – Mr. Alien Apr 01 '20 at 17:03
4

Convert date to MongoDB ISODate format in JavaScript using Moment JS

MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:

  • new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
  • 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.
  • new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.

    var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
    console.log("Next day -- " + (reqDate.getDate() + 1))
    var d = new Date();
    d.setDate(reqDate.getDate() + 1);
    var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');

You can pass today and tomorrow object to MongoDB queries with new Date() shell method.

  MongoClient.connect(con, function (err, db) {
    if (err) throw err
    db.collection('orders').find({ "order_id": store_id, "orderDate": {     
       "$gte": new Date(today), "$lt": new Date(tomorrow)}
     }).toArray(function (err, result) {
        console.log(result);
        if (err) throw err
          res.send(result);
    })
  })
Farrukh Malik
  • 746
  • 9
  • 13