如果把身份證號碼傳到頁面上,在前端頁面獲取年齡就需要用到JS腳本了:
function GetAge(identityCard) { var len = (identityCard + "").length; if (len == 0) { return 0; } else { if ((len != 15) && (len != 18))//身份證號碼只能為15位或18位其它不合法 { return 0; } } var strBirthday = ""; if (len == 18)//處理18位的身份證號碼從號碼中得到生日和性別代碼 { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //時間字符串里,必須是“/” var birthDate = new Date(strBirthday); var nowDateTime = new Date(); var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //再考慮月、天的因素;.getMonth()獲取的是從0開始的,這里進行比較,不需要加1 if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) { age--; } return age; }