比较 MongoDB 中的日期 (moment.js)

Compare date (moment.js) in MongoDB

我想比较 MongoDB 的日期和我的日期。

我也阅读了 and this post 但我没有找到答案。

我的代码:

  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

因此这个构造不起作用,但如果我比较谎言:

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"

有人帮忙吗?

编辑:

  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();

.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()方法:

today: function() {
    var now = moment().toDate();
    return Posts.find({createdAt : { $gte : now }});
}

使用 Moment JS

在 JavaScript 中将日期转换为 MongoDB ISODate 格式

MongoDB 使用 ISODate 作为他们的主要日期类型。如果要将日期对象插入到 MongoDB 集合中,可以使用 Date() shell 方法。

您可以通过将年份在 0 到 9999 之间的 ISO-8601 日期字符串传递给 new Date() 构造函数或 ISODate( ) 功能。这些函数接受以下格式:

  • new Date("<YYYY-mm-dd>") returns 具有指定日期的 ISODate。
  • new Date("<YYYY-mm-ddTHH:MM:ss>") 指定客户端本地时区的日期时间和 returns 具有 UTC 指定日期时间的 ISODate。
  • new Date("<YYYY-mm-ddTHH:MM:ssZ>") 指定 UTC 日期时间,returns 指定 UTC 日期时间的 ISODate。
  • new Date() 将日期时间指定为自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数,以及 returns 生成的 ISODate 实例。

如果您在 JavaScript 中编写代码并且想要传递一个 JavaScript 日期对象并将其与 MongoDB 客户端一起使用,您要做的第一件事就是转换 JavaScript 日期转换为 MongoDB 日期格式 (ISODate)。这是您的操作方法。

    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]');

您可以使用新的 Date() shell 方法将今天和明天的对象传递给 MongoDB 查询。

  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);
    })
  })