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

How do i properly compare dates in moment.js using node.js + mongoose

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

在我的 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

还有一件事,typeof currentDatefuture_month 都是字符串,这就是为什么我将 mongoose 字段作为字符串类型。只是想让你们知道。

您正在尝试比较字符串。这在大多数情况下是行不通的,尤其是对于您使用的格式。相反,比较 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') 通常是午夜,但由于时区和夏令时的原因,并非总是如此。 :)