1. 程式人生 > 實用技巧 >JS中根據身份證號獲取年齡、出生日期

JS中根據身份證號獲取年齡、出生日期

//獲取年齡
function GetAge(身份證號) {

varstrBirthday = "";
if (len == 18)//18位身份證號
{
strBirthday= 身份證號.substr(6, 4) + "/" + 身份證號.substr(10, 2) + "/" + 身份證號.substr(12, 2);
}
if (len == 15)//15位身份證號

{
strBirthday= "19" + 身份證號.substr(6, 2) + "/" + 身份證號.substr(8, 2) + "/" + 身份證號.substr(10, 2);


}

//時間字串裡,必須是“/”隔開
var birthDate = new Date(strBirthday);
var nowDateTime = new Date();
var age = nowDateTime.getFullYear() - birthDate.getFullYear();
//月、天的因素;.getMonth()獲取的是從0開始
if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {


age--;
}
return age;
}

//獲取出生日期

//18位身份證號

var birthday=身份證號.substr(6, 4) + "-" +身份證號.substr(10, 2) + "-" + 身份證號.substr(12, 2);

//15位身份證號

var birthday= "19" + 身份證號.substr(6, 2) + "/" + 身份證號.substr(8, 2) + "/" + 身份證號.substr(10, 2);