比较MongoDB中的日期(moment.js) [英] Compare date (moment.js) in MongoDB

查看:338
本文介绍了比较MongoDB中的日期(moment.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较MongoDB中的日期和我的日期.

I want to compare date from MongoDB and my date.

我也阅读了

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

我的代码:

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

返回

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

推荐答案

> c0> 方法是一种显示帮助器函数,该函数根据传递的令牌参数返回日期字符串表示形式.要将MongoDB中的日期与当前日期和时间进行比较,只需调用 moment() (没有参数),没有 .format() 方法并通过调用 toDate() 方法:

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

这篇关于比较MongoDB中的日期(moment.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆