javascript Moment.js - 在年、月和日内获得两个生日的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33988129/
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 17:06:11  来源:igfitidea点击:

Moment.js - Get difference in two birthdays in years, months and days

javascriptdatemomentjs

提问by Ole-Morten Heggertveit

I'm looking for a way to use momentjs to parse two dates, to show the difference.

我正在寻找一种使用 momentjs 解析两个日期的方法,以显示差异。

I want to have it on the format: "X years, Y months, Z days".

我希望它的格式为:“X 年,Y 个月,Z 天”。

For the years and months the moment library and modulo operator works nice. But for the days it's another tale as I don't want to handle leap years and all that by myself. So far the logic I have in my head is this:

多年来,时刻库和模运算符运行良好。但是对于那些日子,这是另一个故事,因为我不想自己处理闰年之类的事情。到目前为止,我脑子里的逻辑是这样的:

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'years');
var months = a.diff(b, 'months') % 12;
var days = a.diff(b, 'days');
// Abit stuck here as leap years, and difference in number of days in months. 
// And a.diff(b, 'days') returns total number of days.
return years + '' + months + '' + days;

回答by Josh Crozier

You could get the difference in years and add that to the initial date; then get the difference in months and add that to the initial date again.

您可以得到年份的差异并将其添加到初始日期;然后得到以月为单位的差异并将其再次添加到初始日期。

In doing so, you can now easily get the difference in days and avoid using the modulo operator as well.

通过这样做,您现在可以轻松获得天数的差异,并避免使用模运算符。

Example Here

示例在这里

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var years = a.diff(b, 'year');
b.add(years, 'years');

var months = a.diff(b, 'months');
b.add(months, 'months');

var days = a.diff(b, 'days');

console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days

I'm not aware of a better, built-in way to achieve this, but this method seems to work well.

我不知道有更好的内置方法来实现这一点,但这种方法似乎很有效。

回答by Kunal Kapadia

Moment.js also has durationobject. A moment is defined as single point in time, whereas duration is defined as a length of time which is basically what you want.

Moment.js 也有duration对象。片刻被定义为单个时间点,而持续时间被定义为基本上是您想要的时间长度。

var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);

var diffDuration = moment.duration(a.diff(b));

console.log(diffDuration.years()); // 8 years
console.log(diffDuration.months()); // 5 months
console.log(diffDuration.days()); // 2 days

What @Josh suggest may work, but is definitely not the right way of calculating difference in 2 moments.

@Josh 的建议可能有效,但绝对不是计算 2 时刻差异的正确方法。

回答by Muneeb

I just converted @Josh Crozier's answerinto a function and added hours, minutesand secondstoo.

我刚刚将@Josh Crozier 的答案转换为一个函数,并添加了小时分钟

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};
}

回答by Chandresh

Above solution is not working with momentjs 2.19.1

上述解决方案不适用于 momentjs 2.19.1

Then with reference of Date of Joining calculation not working with moment 2.19.1I have implemented new solution with latest solution for momentjs 2.19.1.

然后参考加入日期计算不适用于 moment 2.19.1我已经用最新的解决方案为 momentjs 2.19.1实施了新的解决方案

Required npm packages:

所需的 npm 包

"moment": "^2.19.4",

时刻”:“^2.19.4”,

"moment-duration-format": "^1.3.0",

"瞬间持续时间格式": "^1.3.0",

"react-moment": "^0.6.8",

"反应时刻": "^0.6.8",

import following in reactjs:

在 reactjs 中导入以下内容

 import moment from "moment";
 import Moment from "react-moment";
 import momentDurationFormatSetup from "moment-duration-format";


var DOJ = moment([work_data.joining_date]).format("YYYY,MM,DD");      
var today = moment().format("YYYY,MM,DD");      
var totalMonths =  parseInt(moment(today).diff(moment(DOJ), 'months'));      
var totalDuration = moment.duration(totalMonths, "months").format();      
if(totalDuration.search('1y') > -1) {
   totalDuration = totalDuration.replace("1y", "1 Year,");
} else {
   totalDuration = totalDuration.replace("y", " Years,");
}

if(totalDuration.search('1m') > -1){
  totalDuration = totalDuration.replace("1m", "1 Month");
} else {
  totalDuration = totalDuration.replace("m", " Months");
}

console.log(totalDuration);

回答by Alaksandar Jesus Gene

This is another answer. 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";
}

回答by Abdus Salam Azad

Use this

用这个

  var totalDays = endDate.diff(startDate, "days");