在 JavaScript 中根据我的生日获取 REAL_AGE

我写了一个有效的函数,但我认为它可以写得更好。


  export const getRealAge = () => {

      const today = new Date()

      const DATE_OF_BIRTH = new Date(1997, 9, 16)

      const ONE_DAY = 1000 * 60 * 60 * 24

      const REAL_AGE = Math.round(

        Math.abs((today - DATE_OF_BIRTH) / (ONE_DAY * 365))

      )


      return REAL_AGE

    }


牛魔王的故事
浏览 174回答 2
2回答

森栏

你的解决方案还不错。它提出了一个小的修改,使用@edu 提到的时刻和方法差异(考虑到闰年)库。const today = moment()const birth = moment([1997, 9, 16])const getRealAge = (birth,today) => today.diff(birth,'year')// testconsole.log( getRealAge(birth,today))

ITMISS

我稍微更改了变量名,因为我没有看到这里需要使用大写字母。我也试图使代码尽可能地可读。您的解决方案的问题是它可能不太精确,很难以这种方式考虑闰年。export const getRealAge = (year, month, date) => {&nbsp; const today = new Date();&nbsp; const birthday = new Date(year, month, date);&nbsp; let age = today.getFullYear() - birthday.getFullYear();&nbsp; const monthsDiff = today.getMonth() - birthday.getMonth();&nbsp; const turnsThisMonth = monthsDiff === 0;&nbsp; const turnsAtLaterMonth = monthsDiff < 0;&nbsp; if(turnsAtLaterMonth) {&nbsp; &nbsp; &nbsp; age--;&nbsp; } else if (turnsThisMonth){&nbsp; &nbsp; &nbsp; if (today.getDate() < birthday.getDate()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; age--;&nbsp; &nbsp; &nbsp; }&nbsp; }&nbsp; return age;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript