简体   繁体   中英

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)

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

This is futureMonth value

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

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

and one more thing the typeof currentDate and future_month are both strings, that's why I put mongoose field as a string type. 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.

// 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 . If instead you had today < future , then I'd written it as today.isBefore(future) instead.

Also note that the startOf('day') will usually be midnight, but not always, due to time zones and DST. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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