点击上方蓝字关注我们最近项目上有一个需要根据身份证获取老人周岁的功能,本以为当前年直接减去身份证的出生年就好了。结果测试提了过了生日就是+1岁,没过生日才是正确的。于是呼,哗哗的改代码。下面分别贴出java计算和js计算:
java计算public Integer handleIdentityAge(String identity,Integer year,Integer month,Integer day){ if(identity.length()<10){ return 0; } Integer selectYear=Integer.valueOf(identity.substring(6,10)); Integer selectMonth=Integer.valueOf(identity.substring(10,12)); Integer selectDay = Integer.valueOf(identity.substring(12, 14)); Integer yearMinus = year - selectYear; Integer monthMinus = month - selectMonth; Integer dayMinus = day - selectDay; Integer age = yearMinus; if(yearMinus<0){ age = 0; }else if (yearMinus == 0) { age = 0; } else if (yearMinus > 0) { if (monthMinus == 0) { if (dayMinus < 0) { age = age - 1; } } else if (monthMinus > 0) { age = age + 1; } } return age; }js计算function calculatingAge (identity) { if(identity.length < 10) { return ""; } debugger var birthYear = identity.substr(6, 4); var birthMonth = identity.substr(10, 2); var birthDay = identity.substr(12, 2); var d = new Date(); var nowYear = d.getFullYear(); var nowMonth = d.getMonth() + 1; var nowDay = d.getDate(); let returnAge = 0; let result = 0; //1997-11-16 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;}
以上两种方式都是根据身份证号计算周岁,避免重复造轮子,可以直接复制使用。

版权声明:本文为weixin_35759767原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。