简体   繁体   English

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

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

I have two dates that I would like to compare , current date and future date 我要比较两个日期,当前日期和将来的日期

in my mongodb database (I'm using mongoose as its ORM) 在我的mongodb数据库中(我使用猫鼬作为其ORM)

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

This is futureMonth value 这是futureMonth的值

future_month = moment().add(1, 'M').format('DD-MM-YYYY');

and I tried to compare the current date and future date 我试图比较当前日期和将来的日期

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

I always get "You have to pay" even though 即使我总是得到"You have to pay"

currentDate = 31-10-2015
req.user.future_month = 30/11/2015

It is supposed to run "Still Active" because currentDate is less than req.user.future_month value 由于currentDate小于req.user.future_month值,因此应该运行"Still Active" req.user.future_month "Still Active"

and one more thing the typeof currentDate and future_month are both strings, that's why I put mongoose field as a string type. 另外, currentDatefuture_month类型都是字符串,这就是为什么我把future_month字段设置为字符串类型的原因。 Just to let you guys know. 只是为了让大家知道。

You are trying to compare strings. 您正在尝试比较字符串。 That won't work in most cases, especially with the format you're using. 在大多数情况下,这是行不通的,尤其是对于您使用的格式。 Instead, compare moment objects, and use the built-in functions rather than comparison operators. 而是比较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)) {
    ...

Note that I used isAfter function and flipped the sides of the comparison because you had today <= future , and moment only has isAfter and isBefore . 请注意,我使用了isAfter函数并翻转了比较的两面,因为您today <= future ,而那一刻只有isAfterisBefore If instead you had today < future , then I'd written it as today.isBefore(future) instead. 相反,如果您today < future ,那么我将其写为today.isBefore(future)

Also note that the startOf('day') will usually be midnight, but not always, due to time zones and DST. 另请注意,由于时区和夏令时的原因, startOf('day')通常会在午夜,但并非总是如此。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM