I\'ve been playing around with Moment.js and I\'ve come across a problem. I\'ve been trying to identify whether a date given is in the past or in the future. The dates are
You actually don't need to use .format()
at all for this.
First, the timestamps should be numbers, not strings (ex, var pastUnixTime = 1348812970;
), and second, you can compare them directly:
> pastUnixTime = 1348812970;
> pastUnixTime < moment().unix()
true
> pastUnixTime > moment().unix()
false
Now, the reason your code is failing is that when you compare the DD MM YYYY
strings, they are being compared lexicographically… And the days are first! So the string "01 01 2000"
will always be "less than" "31 12 1900"
. If you wanted to compare strings, you could use YYYY MM DD
format — that way, "2000 01 01"
will be correctly "greater than" "1900 12 31"
. But there's no reason to do that - timestamps are much more straight forward.
Finally, a note: you don't actually need to use the .unix()
- instances of moment()
will compare sensibly:
> past = moment().subtract("days", 1)
> now = moment()
> past < now
true
> past > now
false