前言:

根据身份证号判断精确周岁年龄,可以精确到天,即周岁以生日当天为准,生日当天周岁+1,少一天则不加。

实现方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script> /**
* 根据身份证号,获取精缺周岁年龄
* @param {Object} strBirthday 生日格式:19880808
*/
function getAgeByPid(strBirthday){
var birthYear = strBirthday.substr(0,4)
var birthMonth = strBirthday.substr(4,2)
var birthDay = strBirthday.substr(6,2) d = new Date();
var nowYear = d.getFullYear();
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;//返回周岁年龄
}
/**
* 获取年龄的单击事件
*/
function getAge(){
var pid=document.getElementById("txtPid").value;
pid=pid.substr(6,8)
alert(getAgeByPid(pid))
}
</script>
<input type="text" name="pid" id="txtPid">
<input type="button" value="查询" id="btnGetAge" onclick="getAge()">
</body>
</html>
05-02 20:13