Skip to content
Advertisement

Moment JS Date Difference as Month

I’m trying to get the difference between current local time and December 1, 2021 at 4 pm. There is a difference of 6 months and 2 hours. In this case I expect the answer to be something similar to 6.02. But 5.98 is coming. How can I get the answer I want?

enter image description here

Advertisement

Answer

According to the moment.js docs, the standard way to get the difference between two dates in your example would be now.diff(date, 'months', true), which should return a floating point number greater than 6.

now.diff(date) returns the millisecond difference between those two points in time. Calling moment.duration({milliseconds}).asMonths() is not ideal because some months may be 30 days long and others may be 31 days long. It appears that moment.js uses somewhere in between 30 and 31 days as the duration of one month. To address this issue, moment.js have discussed calendar diffs in the docs:

moment#diff has some special handling for month and year diffs. It is optimized to ensure that two months with the same date are always a whole number apart.

So Jan 15 to Feb 15 should be exactly 1 month.

Feb 28 to Mar 28 should be exactly 1 month.

Feb 28 2011 to Feb 28 2012 should be exactly 1 year.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement