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

时间:2015-10-31 04:11:23

标签: node.js mongoose momentjs

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

在我的mongodb数据库中(我使用mongoose作为其ORM)

var User = mongoose.Schema({
    future_month: String
});

这是futureMonth值

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

即使

,我总是得到"You have to pay"
currentDate = 31-10-2015
req.user.future_month = 30/11/2015

应该运行"Still Active",因为currentDate小于req.user.future_month

还有一个类型currentDatefuture_month都是字符串,这就是我将mongoose字段作为字符串类型的原因。只是为了让你们知道。

1 个答案:

答案 0 :(得分:0)

您正在尝试比较字符串。这在大多数情况下都不起作用,特别是对于您正在使用的格式。相反,比较moment个对象,并使用内置函数而不是比较运算符。

// 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功能并翻转了比较的两侧,因为您有today <= future,而且时刻只有isAfterisBefore。如果您有today < future,那么我会将其写为today.isBefore(future)

另请注意,由于时区和夏令时,startOf('day')通常是午夜,但并非总是如此。 :)