我想根据一个人的出生日期计算他的年龄。
我知道可以通过 moment().diff(date_of_birth, 'months') 返回自出生以来的月数或年数
。
我想返回一些更具体的内容,如下所示:
23 天
(如果该人出生不到一个月)或2 个月
或1 年2 个月
我们可以用 Momentjs 做到这一点吗?
最佳答案
试试这个
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();
关于javascript - 如何用Momentjs精确计算年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51716567/