Reputation: 3417
I'm trying to compare two dates. I want to check and see if one date is before another. I'm using momentjs and everything I do seems to return false
. Any help would be appreciated.
Format - [Month, Year]
moment([0, 2012]).isBefore([1, 2013]);
Upvotes: 2
Views: 12539
Reputation: 1027
It will always give you an invalid date the way you have coded it. There are many ways to construct the date using moment. Try this:
var a = moment([2012, 0]);
var b = moment([2013, 1]);
console.log(a.isBefore(b)); //returns true
On the same note, please read the docs carefully on the usage of "0" as the month, before and after version 2.1.0:
Months are zero indexed, so January is month 0.
Before version 2.1.0, if a moment changed months and the new month did not have enough days to keep the current day of month, it would overflow to the next month.
// before 2.1.0
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD"); // 2012-03-02
As of version 2.1.0, this was changed to be clamped to the end of the target month.
// after 2.1.0
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD"); // 2012-02-29
Upvotes: 6
Reputation: 3417
What seems to work is this:
var a = moment({month: 0, year: 2012});
var b = moment({month: 2, year: 2014});
console.log(a.isBefore(b))
Upvotes: 0