本文我們主要和大家分享JS實現根據出生日期得到年齡方法,希望能幫助大家。
JavaScript//JS根据出生日期 得到年龄 //参数strBirthday已经是正确格式的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根据出生日期 得到年龄 //参数strBirthday已经是正确格式的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;//返回周岁年龄 }# #JS實作兩個日期比較相差多少天的案例mysql如何自動取得時間日期的實例詳解
以上是JS實現根據出生日期得到年齡方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!