如何用Momentjs精确计算年龄?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1163)

我想计算一个人从出生之日起的年龄。

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

我想返回一些更具体的东西,如:

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

能用Momentjs实现吗?

提问于
用户回答回答于

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

如moment diff(https://momentjs.com/docs/#/displaying/difference/)显示的:

By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.

如下所示:

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>

用户回答回答于

试试这个。

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

所属标签

可能回答问题的人

  • 找虫虫

    0 粉丝0 提问5 回答
  • 骑牛看晨曦

    4 粉丝522 提问4 回答
  • 爸爸

    腾讯 · 客户端安全 (已认证)

    3 粉丝4 提问4 回答
  • 不吃貓的鱼oo

    5 粉丝466 提问4 回答

扫码关注云+社区

领取腾讯云代金券