如何使用moment.js获得年,月和日的2个日期之间的差异 [英] How to get difference between 2 Dates in Years, Months and days using moment.js
问题描述
如何使用moment.js获得年,月和日的2个日期之间的差异?
例如 4/5/2014 & 2/22/2013 应计算为 1年,1个月和14天。
How to get difference between 2 Dates in Years, Months and days using moment.js? For example the difference between 4/5/2014 & 2/22/2013 should be calculated as 1 Year, 1 Month and 14 Days.
推荐答案
Moment.js无法直接处理此场景。它允许您获取两个时刻之间的差异,但结果是经过的持续时间(以毫秒为单位)。片刻确实有一个持续时间对象,但它将一个月定义为30天的固定单位 - 我们知道情况并非总是如此。
Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.
幸运的是,已经创建了一个名为精确范围,这是正确的做法。查看来源,它有所作为类似于 torazaburo的答案 - 但它恰当地说明了要调整的月份天数。
Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.
在你的项目中包含了moment.js和这个插件(readable-range.js)后,你可以这样简单地调用它:
After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:
var m1 = moment('2/22/2013','M/D/YYYY');
var m2 = moment('4/5/2014','M/D/YYYY');
var diff = moment.preciseDiff(m1, m2);
console.log(diff);
输出为1年1个月14天
The output is "1 year 1 month 14 days"
这篇关于如何使用moment.js获得年,月和日的2个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!