Moment.js - 在两年,几个月和几天的生日中获得差异

时间:2015-11-29 21:06:24

标签: javascript date momentjs

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

我希望格式化:" X年,Y个月,Z天"。

数年和数月,库和模运算符的工作效果很好。但对于那些日子而言,这是另一个故事,因为我不想处理闰年和我自己的所有这些。到目前为止,我脑子里的逻辑是:

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;

6 个答案:

答案 0 :(得分:30)

您可以获得多年的差异并将其添加到初始日期;然后在几个月内得到差异并再次将其添加到初始日期。

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

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

我不知道有更好的内置方法来实现这一目标,但这种方法似乎运行良好。

答案 1 :(得分:25)

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

@Josh建议可能有用,但绝对不是在2分钟内计算差异的正确方法。

答案 2 :(得分:0)

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

然后参考Date of Joining calculation not working with moment 2.19.1我已经使用最新解决方案实现了新的解决方案,适用于时刻2.19.1

必需的npm包

" moment":" ^ 2.19.4",

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

" react-moment":" ^ 0.6.8",

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

答案 3 :(得分:0)

这是另一个答案。通过年龄计算器验证

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";
}

答案 4 :(得分:0)

我刚刚将Josh Crozier的answer转换为函数,并且还添加了小时分钟

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

答案 5 :(得分:-1)

使用此

>>> print(left_rotation(5,2,[1,2,3,4,5]))
1
2
3
4
5
[3, 4, 5, 1, 2]