代码之家  ›  专栏  ›  技术社区  ›  user3142695

使用momentJS计算年龄并获得不同的输出字符串

  •  2
  • user3142695  · 技术社区  · 6 年前

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

    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
    

    如何计算这些输出?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Akrion    6 年前

    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>

    它依赖于瞬间,最主要的是它的使用 moment.diff 在一个 moment.duration . 从这一点上说,它只是得到了正确的持续时间在正确的部分 form (指年/月/日)。

    我还没有做广泛的测试,所以请随意拨弄,看看它是否不能处理一些案件100%。