javascript 如何使用moment.js获取年、月和日中的2个日期之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26063882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:26:34  来源:igfitidea点击:

How to get difference between 2 Dates in Years, Months and days using moment.js

javascriptmomentjs

提问by Nick

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/2013should be calculated as 1 Year, 1 Month and 14 Days.

如何使用moment.js获取年、月和日中的2个日期之间的差异?例如之间的差2014年4月5日2013年2月22日应该被计算为1年,1月和14天

回答by Matt Johnson-Pint

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 Durationobject, but it defines a month as a fixed unit of 30 days - which we know is not always the case.

Moment.js 无法直接处理这种情况。它确实允许您获取两个时刻之间的差异,但结果是经过的持续时间(以毫秒为单位)。Moment 确实有一个Duration对象,但它将一个月定义为 30 天的固定单位——我们知道情况并非总是如此。

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.

幸运的是,已经创建了一个名为“Precise Range”的插件,它可以做正确的事情。查看源代码,它的功能类似于torazaburo 的答案- 但它正确地考虑了要调整的月份中的天数。

After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:

在你的项目中包含 moment.js 和这个插件 (readable-range.js) 之后,你可以简单地像这样调用它:

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);

The output is "1 year 1 month 14 days"

输出为“1年1月14天”

回答by Nick

You hardly need moment.

你几乎不需要时刻。

d1 = new Date(2014, 3, 5);                // April 5, 2014
d2 = new Date(2013, 1, 22);               // February 22, 2013
diff = new Date(
    d1.getFullYear()-d2.getFullYear(), 
    d1.getMonth()-d2.getMonth(), 
    d1.getDate()-d2.getDate()
);

This takes advantage of the fact that the Dateconstructor is smart about negative values. For instance, if the number of months is negative, it will take that into account and walk back the year.

这利用了Date构造函数对负值很聪明的事实。例如,如果月数为负数,它会考虑到这一点并返回年份。

console.log(diff.getYear(), "Year(s),", 
    diff.getMonth(), "Month(s), and", 
    diff.getDate(), "Days.");

>> 1 Year(s), 1 Month(s), and 11 Days. 

Your calculation is wrong--it's not 14 days, it's six remaining days in February and the first five days of April, so it's 11 days, as the computer correctly computes.

你的计算是错误的——它不是 14 天,它是二月剩下的六天和四月的前五天,所以是 11 天,因为计算机正确计算。

Second try

第二次尝试

This might work better given @MattJohnson's comment:

鉴于@MattJohnson 的评论,这可能会更好:

dy = d1.getYear()  - d2.getYear();
dm = d1.getMonth() - d2.getMonth();
dd = d1.getDate()  - d2.getDate();

if (dd < 0) { dm -= 1; dd += 30; }
if (dm < 0) { dy -= 1; dm += 12; }

console.log(dy, "Year(s),", dm, "Month(s), and", dd, "Days.");

回答by Alaksandar Jesus Gene

This worked for me. Verified with Age calculator.

这对我有用。用年龄计算器验证。

function calculateAge(){
    ageText = jQuery("#dob").closest(".form-group").find(".age-text");
    ageText.text("");
    level2.dob = jQuery("#dob").val();
    if(!level2.dob) return;
    level2.mdob= moment(level2.dob, 'DD-MM-YYYY');
    if(!level2.mdob.isValid()){
        alert("Invalid date format");
        return;
    }
    level2.targetDate = moment();//TODO: Fill in the target date
    level2.months = level2.targetDate.diff(level2.mdob, 'months'); // Calculate the months
    let years = parseInt(level2.months/12); // A year has 12 months irrespective or leap year or not
    let balanceMonths = level2.months%12; // The balance gives the number of months 
    let days;
    if(!balanceMonths){ // If no balance months, then the date selected lies in the same month
        months = 0; // so months = 0
        days = level2.targetDate.diff(level2.mdob, 'days'); // only the days difference
    }else{
    months = balanceMonths;
    dob_date = level2.mdob.date();
    target_month = level2.targetDate.month();
    construct_date = moment().month(target_month).date(dob_date);
    days = level2.targetDate.diff(construct_date, 'days')+1; // There might be one day missed out. Not sure on UTC
}

ageText = years +" years " + months+ " months " + days +" days";
}