本文我們主要和大家分享JS實(shí)現(xiàn)根據(jù)出生日期得到年齡方法,希望能幫助到大家。
JavaScript//JS根據(jù)出生日期 得到年齡 //參數(shù)strBirthday已經(jīng)是正確格式的2017-12-12這樣的日期字符串 function jsGetAge(strBirthday) { var returnAge; var strBirthdayArr=strBirthday.split("-"); var birthYear = strBirthdayArr[0]; var birthMonth = strBirthdayArr[1]; var birthDay = strBirthdayArr[2]; var d = new Date(); var nowYear = d.getYear(); var nowMonth = d.getMonth() + 1; var nowDay = d.getDate(); if(nowYear == birthYear) { returnAge = 0;//同年 則為0歲 } else { var ageDiff = nowYear - birthYear ; //年之差 if(ageDiff > 0) { if(nowMonth == birthMonth) { var dayDiff = nowDay - birthDay;//日之差 if(dayDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff ; } } else { var monthDiff = nowMonth - birthMonth;//月之差 if(monthDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff ; } } } else { returnAge = -1;//返回-1 表示出生日期輸入錯誤 晚于今天 } } return returnAge;//返回周歲年齡 }
JavaScript//JS根據(jù)出生日期 得到年齡 //參數(shù)strBirthday已經(jīng)是正確格式的2017-12-12這樣的日期字符串 function jsGetAge(strBirthday) { var returnAge; var strBirthdayArr=strBirthday.split("-"); var birthYear = strBirthdayArr[0]; var birthMonth = strBirthdayArr[1]; var birthDay = strBirthdayArr[2]; var d = new Date(); var nowYear = d.getYear(); var nowMonth = d.getMonth() + 1; var nowDay = d.getDate(); if(nowYear == birthYear) { returnAge = 0;//同年 則為0歲 } else { var ageDiff = nowYear - birthYear ; //年之差 if(ageDiff > 0) { if(nowMonth == birthMonth) { var dayDiff = nowDay - birthDay;//日之差 if(dayDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff ; } } else { var monthDiff = nowMonth - birthMonth;//月之差 if(monthDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff ; } } } else { returnAge = -1;//返回-1 表示出生日期輸入錯誤 晚于今天 } } return returnAge;//返回周歲年齡 }
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com