How do i properly compare dates in moment.js using node.js + mongoose -
i have 2 dates compare , current date , future date
in mongodb database (i'm using mongoose orm)
var user = mongoose.schema({ future_month: string });
this futuremonth value
future_month = moment().add(1, 'm').format('dd-mm-yyyy');
and tried compare current date , 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 pay"); } }
i "you have pay"
though
currentdate = 31-10-2015 req.user.future_month = 30/11/2015
it supposed run "still active"
because currentdate
less req.user.future_month
value
and 1 more thing typeof currentdate
, future_month
both strings, that's why put mongoose field string type. let guys know.
you trying compare strings. won't work in cases, format you're using. instead, compare moment
objects, , use built-in functions rather comparison operators.
// start of current date, moment object var today = moment().startof('day'); // parse input string moment object using format matches var future = moment(req.user.future_month, "dd/mm/yyyy"); // use isafter function compare if (future.isafter(today)) { ...
note used isafter
function , flipped sides of comparison because had today <= future
, , moment has isafter
, isbefore
. if instead had today < future
, i'd written today.isbefore(future)
instead.
also note startof('day')
midnight, not always, due time zones , dst. :)
Comments
Post a Comment