为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

牛魔王的故事 2022-05-26 17:56:04
我写了一个有效的函数,但我认为它可以写得更好。  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    }
查看完整描述

2 回答

?
森栏

TA贡献1810条经验 获得超5个赞

你的解决方案还不错。它提出了一个小的修改,使用@edu 提到的时刻和方法差异(考虑到闰年)库。


const today = moment()

const birth = moment([1997, 9, 16])


const getRealAge = (birth,today) => today.diff(birth,'year')


// test

console.log( getRealAge(birth,today))


查看完整回答
反对 回复 2022-05-26
?
ITMISS

TA贡献1871条经验 获得超8个赞

我稍微更改了变量名,因为我没有看到这里需要使用大写字母。我也试图使代码尽可能地可读。


您的解决方案的问题是它可能不太精确,很难以这种方式考虑闰年。


export const getRealAge = (year, month, date) => {

  const today = new Date();

  const birthday = new Date(year, month, date);

  let age = today.getFullYear() - birthday.getFullYear();

  const monthsDiff = today.getMonth() - birthday.getMonth();

  const turnsThisMonth = monthsDiff === 0;

  const turnsAtLaterMonth = monthsDiff < 0;

  if(turnsAtLaterMonth) {

      age--;

  } else if (turnsThisMonth){

      if (today.getDate() < birthday.getDate()) {

          age--;

      }

  }

  return age;

}


查看完整回答
反对 回复 2022-05-26
  • 2 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号