首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用Momentjs精确计算年龄?

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

Stack Overflow用户
提问于 2018-08-07 06:42:58
回答 1查看 2.1K关注 0票数 0

我想从一个人的出生日期算出他的年龄。

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

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

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

我们能用Momentjs做到这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2018-08-07 06:59:48

尝尝这个

代码语言:javascript
运行
复制
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();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51716567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档