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
?
Compare two dates using Moment.Moment. js has a diff() method, which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the second unit in our case to find the difference between the two dates.
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().
Moment.js has been successfully used in millions of projects, and we are happy to have contributed to making date and time better on the web. As of September 2020, Moment gets over 12 million downloads per week!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With