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?
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.
The definition of "a month" can only be a "fuzzy" one, as the months of the calendar are of different lengths. One way of defining it would be to divide the year into 12 equal parts and use that as a "month-metric":
发布评论
评论(2)
根据 now.diff(日期,'note,true),它应该返回一个大于6的浮点数。
现在。 diff(date)
返回这两个时间点之间的毫秒差。调用moment.duration({milliseconds})。Asmonths()
不是理想的,因为有些月可能是30天,而其他人可能长31天。看来那一刻。为了解决这个问题,Moment.js讨论了文档中的日历差异: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. Callingmoment.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:“一个月”的定义只能是一个“模糊”,因为日历的几个月的长度不同。定义的一种方法是将年度分为12个平等部分,并将其用作“月份”:
The definition of "a month" can only be a "fuzzy" one, as the months of the calendar are of different lengths. One way of defining it would be to divide the year into 12 equal parts and use that as a "month-metric":