. Advertisement .
. Advertisement .
What is Moment.js?
Moment JS enables the presentation of dates in a localized and legible manner. The script approach of using MomentJS enables you to use it inside a browser. It can be installed via npm and is also compatible with Node.js.
You can easily add, subtract, validate dates, retrieve the maximum and minimum dates, and more with MomentJS. It is an open source project, so you can easily add functionality by creating plugins, make the library available in Node.js and on GitHub.
How to compare only dates in Moment.js
Solution 1: Utilize the isAfter method
To compare only dates in Moment.js, you can use the isAfter method to determine whether one date comes after another or not. For example:
const isAfter = moment('2010-10-20').isAfter('2010-01-01', 'year'); // Compare Dates Moment js console.log(isAfter)
You use a date string to build a moment object. Then, using a different date string and the unit to compare, you call isAfter on it. Because you are only comparing the year, isAfter is false.
Solution 2: Utilize the isSameOrAfter method
You may also compare if a date is the same as or after a specified unit using the isSameOrAfter method, which accepts the same inputs.
If you have:
// Compare Dates in Moment.js const isSameOrAfter = moment('2010-10-20').isSameOrAfter('2010-01-01', 'year'); console.log(isSameOrAfter)
Given that 2010 is the same year for both dates, so isSameOrAfter is true.
Solution 3: Utilize the isBefore function
The isBefore function allows you to determine if one date is prior to another which is offered the unit to compare.
Another case, if you have:
const isBefore = moment('2010-10-20').isBefore('2010-01-01', 'year'); console.log(isBefore)
false because their years are similar.
isSame will compare if 2 dates have the similar unit.
const isSame = moment('2010-10-20').isSame('2010-01-01', 'year'); console.log(isSame)
In this case, both of their years are 2010, so
For those who are still bothered by this issue, the recommendation depicted in the figure above has proven to be the most useful knowledge for solutions to compare dates in Moment.js. If you still need help or have any questions, we have a lively group where everyone is always willing to support you any time. Finally, we wish all of you a fantastic day filled with new program topics and see you in the other concepts.
→ Solution to get the difference between two dates in days, month, and years running moment.js
Leave a comment