第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在 JavaScript 中根據(jù)我的生日獲取 REAL_AGE

在 JavaScript 中根據(jù)我的生日獲取 REAL_AGE

牛魔王的故事 2022-05-26 17:56:04
我寫(xiě)了一個(gè)有效的函數(shù),但我認(rèn)為它可以寫(xiě)得更好。  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貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊

你的解決方案還不錯(cuò)。它提出了一個(gè)小的修改,使用@edu 提到的時(shí)刻和方法差異(考慮到閏年)庫(kù)。


const today = moment()

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


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


// test

console.log( getRealAge(birth,today))


查看完整回答
反對(duì) 回復(fù) 2022-05-26
?
ITMISS

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊

我稍微更改了變量名,因?yàn)槲覜](méi)有看到這里需要使用大寫(xiě)字母。我也試圖使代碼盡可能地可讀。


您的解決方案的問(wèn)題是它可能不太精確,很難以這種方式考慮閏年。


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;

}


查看完整回答
反對(duì) 回復(fù) 2022-05-26
  • 2 回答
  • 0 關(guān)注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)