如何使用Momentjs精确计算年龄?

时间:2018-08-06 22:42:58

标签: javascript momentjs

我想计算一个人的出生日期。

我知道可以通过moment().diff(date_of_birth, 'months')返回自出生以来的月数或年数。

我想返回更具体的内容,例如:

23 days(如果该人不到一个月大)或2 months1 year 2 months

我们可以用Momentjs做到吗?

2 个答案:

答案 0 :(得分:1)

尝试一下

let duration = moment.duration(moment().diff('1987-11-15'));
const formatDuration = (duration) => {
    let years = duration.years();
    let months= duration.months();
    let days= duration.days();
    let result = '';
    if (years === 1) {
        result += 'one year ';
    } else if (years > 1) {
        result += years + ' years ';
    }
    if (months === 1) {
        result += 'one month ';
    } else if (months > 1) {
        result += months + ' months ';
    }
    if (days === 1) {
        result += 'one day ';
    } else if (days > 1) {
        result += days + ' days ';
    }
    return result;
}

console.log('Your age is ', formatDuration(duration) );

// you may also try this.
duration.humanize();

答案 1 :(得分:1)

the third paramter=true使用moment.diff应该是一种选择。

moment diff said

  

默认情况下,moment#diff会将结果截断为零小数   位,返回一个整数。如果您想要一个浮点数,   将true作为第三个参数传递。 2.0.0之前,moment#diff返回了一个   四舍五入到最接近的整数,而不是四舍五入的数字。

就像下面的演示一样:

function displayAge(birth, target) {
  let months = target.diff(birth, 'months', true)
  let birthSpan = {year: Math.floor(months/12), month: Math.floor(months)%12, day: Math.round((months%1)*target.daysInMonth(),0)}
  // you can adjust below logic as your requirements by yourself
  if (birthSpan.year < 1 && birthSpan.month < 1) {
    return birthSpan.day + ' day' + (birthSpan.day > 1 ? 's' : '')
  } else if (birthSpan.year < 1) {
    return birthSpan.month + ' month' + (birthSpan.month > 1 ? 's ' : ' ') + birthSpan.day + ' day' + (birthSpan.day > 1 ? 's' : '')
  } else if (birthSpan.year < 2) {
    return birthSpan.year + ' year' + (birthSpan.year > 1 ? 's ' : ' ') + birthSpan.month + ' month' + (birthSpan.month > 1 ? 's ' : '')
  } else {
    return birthSpan.year + ' year' + (birthSpan.year > 1 ? 's' : '')
  }
  
}
let birth = moment([1997, 3, 7])
console.log(displayAge(birth, moment()))
console.log(displayAge(birth, moment([1997, 3, 8])))
console.log(displayAge(birth, moment([1997, 3, 10])))
console.log(displayAge(birth, moment([1997, 4, 8])))
console.log(displayAge(birth, moment([1998, 4, 8])))
console.log(displayAge(birth, moment([1998, 5, 8])))
console.log(displayAge(birth, moment([1999, 4, 8])))
<script src="https://momentjs.com/downloads/moment.js"></script>