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 stored as Unix timestamps. So when I'm comparing future dates with current dates, it's working ok, but it's not triggering for past dates. The sample code is below and a fiddle is here.
var pastUnixTime = '1348812970'; //some time in the past
var futureUnixTime = '1352350231';
if (moment.unix(futureUnixTime).format('DD MM YYYY') > moment().format('DD MM YYYY')) {
console.log('yay');
}
if (moment.unix(pastUnixTime).format('DD MM YYYY') < moment().format('DD MM YYYY')) {
console.log('yay 2');
}
The above code logs yay
not not yay 2
. Can anybody explain to me why is it not logging yay 2
?
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