如何使用node.js+;正确比较moment.js中的日期;猫鼬

如何使用node.js+;正确比较moment.js中的日期;猫鼬,node.js,mongoose,momentjs,Node.js,Mongoose,Momentjs,我想比较两个日期,当前日期和未来日期 exports.isTrue = function() { var currentDate = moment().format("DD-MM-YYYY"); if (currentDate <= req.user.future_month) { console.log("Still Active"); } else { console.log("You have to pay"); } }

我想比较两个日期,当前日期和未来日期

exports.isTrue = function() {
    var currentDate = moment().format("DD-MM-YYYY");
    if (currentDate <= req.user.future_month) {
       console.log("Still Active");
    } else {
       console.log("You have to pay");
    }
}
在我的mongodb数据库中(我使用mongoose作为它的ORM)

这是未来月份的值

future_month = moment().add(1, 'M').format('DD-MM-YYYY');
我试着比较当前日期和未来日期

exports.isTrue = function() {
    var currentDate = moment().format("DD-MM-YYYY");
    if (currentDate <= req.user.future_month) {
       console.log("Still Active");
    } else {
       console.log("You have to pay");
    }
}
它应该运行
“仍处于活动状态”
,因为
currentDate
小于
req.user.future\u月


还有一件事,
currentDate
future\u month
的类型都是字符串,这就是为什么我把mongoose字段作为字符串类型。只是想让你们知道。

你们正在尝试比较字符串。这在大多数情况下都不起作用,尤其是在您使用的格式中。相反,请比较
力矩
对象,并使用内置函数而不是比较运算符

// get the start of the current date, as a moment object
var today = moment().startOf('day');

// parse the input string to a moment object using the format that matches
var future = moment(req.user.future_month, "DD/MM/YYYY");

// use the isAfter function to compare
if (future.isAfter(today)) {
    ...

请注意,我使用了
isAfter
函数并翻转了比较的侧面,因为您今天有
您注意到两个日期字符串的格式了吗?
31-10-2015
30/11/2015
使用字符串存储日期并进行比较是一个非常糟糕的主意。这里的问题很简单:“31”在比较字符串时优于“30”,因此您的
currentDate
在“您的
future\u month
之后。非常感谢您提供了一个很好的答案,但我们想知道是否可以使用矩().toDate()而不是矩().startOf('day'))
toDate
为您提供了一个等价日期和时间的
Date
对象。请记住,
Date
的名称有误,它总是一个日期和时间
startOf('day')
将其作为
时刻
对象保存,并将时间移到一天的开始。
// get the start of the current date, as a moment object
var today = moment().startOf('day');

// parse the input string to a moment object using the format that matches
var future = moment(req.user.future_month, "DD/MM/YYYY");

// use the isAfter function to compare
if (future.isAfter(today)) {
    ...