3

This is how I'm calculating the age of a person via moment:

const age = moment().diff('1980-01-01', 'years', false)

But as I also need to get the current age of children and babies, I need to get the output like these four examples:

30 years          // adults
1 year 2 months   // for all <18 years
2 months 12 days  // for all <1 year and > 1 month
20 days           // for all <1 month

How do I calculate those outputs?

user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Take a look at this post - https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd, I think it will help you – tomer raitz Oct 06 '18 at 11:47

1 Answers1

2

Here is a function which would do this for you:

const pluralize = (str, n) => n > 1 ? `${n} ${str.concat('s')}` : n == 0 ? '' :`${n} ${str}`

const calcAge = (dob) => {
  const age = moment.duration(moment().diff(moment(dob)))
  const ageInYears = Math.floor(age.asYears())
  const ageInMonths = Math.floor(age.asMonths())
  const ageInDays = Math.floor(age.asDays())

  if (age < 0)
    throw 'DOB is in the future!'

  let pluralYears = pluralize('year', ageInYears)
  let pluralDays = pluralize('day', age.days())

  if (ageInYears < 18) {
    if (ageInYears >= 1) {
      return `${pluralYears} ${pluralize('month', age.months())}`
    } else if (ageInYears < 1 && ageInMonths >= 1) {
      return `${pluralize('month', ageInMonths)} ${pluralDays}`
    } else {
      return pluralDays
    }
  } else {
    return pluralYears
  }

}

console.log(calcAge('2000-01-01')) // 18 Years
console.log(calcAge('2011-05-01')) // 7 years 5 months
console.log(calcAge('2015-10-01')) // 3 years 
console.log(calcAge('2017-05-01')) // 1 year 5 months
console.log(calcAge('2018-09-01')) // 1 month 5 days
console.log(calcAge('2018-10-01')) // 6 days
console.log(calcAge('2018-07-07')) // 3 months
console.log(calcAge('2099-12-01')) // Uncaught DOB is in the future!
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

It relies on moment and main thing is it uses moment.diff in a moment.duration. From that point it is just getting the right parts of that duration in the right form (meaning years/months/days).

I have not done extensive testing so feel free to poke around and see if it does not handle some cases 100%.

Akrion
  • 18,117
  • 1
  • 34
  • 54