javascript - How to calculate an age precisely with Momentjs? - Stack Overflow

I would like to calculate the age of a person from his date of birth.I know it's possible to retur

I would like to calculate the age of a person from his date of birth.

I know it's possible to return the number of months or years since birth through moment().diff(date_of_birth, 'months').

I would like to return something more specific, like this:

23 days (if the person is less than a month old) or 2 months or 1 year 2 months

Can we do that with Momentjs?

I would like to calculate the age of a person from his date of birth.

I know it's possible to return the number of months or years since birth through moment().diff(date_of_birth, 'months').

I would like to return something more specific, like this:

23 days (if the person is less than a month old) or 2 months or 1 year 2 months

Can we do that with Momentjs?

Share asked Aug 6, 2018 at 22:42 JeremyJeremy 1,9624 gold badges27 silver badges50 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try this

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

Use the third paramter=true for moment.diff should be one option.

As moment diff said:

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.

like below demo:

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./downloads/moment.js"></script>

TS version for Rainer plummer answer

   const duration = moment.duration(moment().diff('1987-11-15'));
    const formatDuration = (duration: moment.Duration) => {
        const years = duration.years();
        const months = duration.months();
        const 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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742404405a4437554.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信